Software
Vue.js: No image displayed when binding data URI to src attribute of img element
I'm passing a data URI as a prop to a Vue component and binding it to the src attribute of an img element, but the image does not appear. Here's the relevant code:
Passing the prop to the component (ignore the image_ratio key name, it's a data URI):
<media-image v-if="event.media_type === 'image'" :url="event.media_url" :caption="event.media_caption" :imageUri="event.image_ratio"></media-image>Accepting the prop within the component:
props: [ 'url', 'caption', 'imageUri' ],And using binding the src to the prop:
<img :src="imageUri" :data-src="url" class="img-fluid" :id="imageId" :alt="caption">Other relevant info:
- The prop is successfully being passed to the component (it appears as a prop using vue-devtools).
- The data URI appears in the DOM as the src of the img element when inspecting it using DevTools.
- Copying the data URI and using it as the src of an img element outside of a Vue component works fine.
Thanks!
When I change router-link not working jquery plugins, but when I refresh it's working
I have SPA with Laravel and I have main.js file and I set up this file in my main.blade.php file and I write some code in main.js with jquery plugins. Problem is when I change vue-router not working this plugins so main.js file, but when I refresh page everything is fine working.Any idea?
VUE : state variable undefined when accessing it in data() section through computed mapGetters()
I've been using ...mapGetters a lot in my solution with success, but now that i need to access the variable directly in the data() section, it seems that the variable isn't set/ready when accessed..
the mapGetters are in the computed:{} section..
When debugging i notice that data() runs before computed:, so.. do i need to put a watch in some way here ?
Code :
data(){ return { FiltersVisible: false, orderList: { currentPage: 1, totalPages: ordersCount / 20, // totalPages:80, itemsPerPage: 20 } } }, computed: { ...mapGetters(['orders', 'ordersCount']) // ...mapGetters(['orders']) },Screenshot of Vue state (Chrome)
Notice that the getters are initialized correctly....
Vuex - passing multiple parameters to action
I am trying to authenticate a user using vuejs and laravel's passport.
I am not able to figure out how to send multiple parameters to the vuex mutation via an action.
- store -
- login method -
login() { var data = { client_id: 2, client_secret: '**************************', grant_type: 'password', username: this.email, password: this.password } // send data this.$http.post('oauth/token', data) .then(response => { // this part is not working this.$store.dispatch({ type: 'authenticate', token: response.body.access_token, expiration: response.body.expires_in + Date.now() }) }) }
I would be very thankful for any kind of help!
npm ERR! Unexpected end of JSON input
I have a project with vuejs on frontend and after I did merge with another branch from a colleague I tried to install a module but I got this error:
npm ERR! Unexpected end of JSON inputThe project works fine, but the problem is that I can't use npm install or update, etc. I have no idea in what file is the error. I tried
npm cache clean --forcebut still the same error.
This is the whole error from debug.log
0 info it worked if it ends with ok 1 verbose cli [ 'C:\Program Files\nodejs\node.exe', 1 verbose cli 'C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js', 1 verbose cli 'i' ] 2 info using npm@5.0.3 3 info using node@v8.1.4 4 verbose npm-session 2706d6ef334eddd9 5 silly install runPreinstallTopLevelLifecycles 6 silly preinstall company@1.0.0 7 info lifecycle company@1.0.0preinstall: company@1.0.0 8 silly lifecycle company@1.0.0preinstall: no script for preinstall, continuing 9 silly install loadCurrentTree 10 silly install readLocalPackageData 11 silly install loadIdealTree 12 silly install cloneCurrentTreeToIdealTree 13 silly install loadShrinkwrap 14 verbose stack SyntaxError: Unexpected end of JSON input 14 verbose stack at JSON.parse () 14 verbose stack at module.exports (C:\Program Files\nodejs\node_modules\npm\lib\utils\parse-json.js:3:15) 14 verbose stack at BB.join (C:\Program Files\nodejs\node_modules\npm\lib\install\read-shrinkwrap.js:31:20) 14 verbose stack at tryCatcher (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\util.js:16:23) 14 verbose stack at Holder$3._callFunction (eval at generateHolderClass (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\join.js:92:16), :14:44) 14 verbose stack at Holder$3.checkFulfillment (eval at generateHolderClass (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\join.js:92:16), :29:30) 14 verbose stack at Promise.eval (eval at thenCallback (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\join.js:14:16), :6:20) 14 verbose stack at Promise._settlePromise (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:566:21) 14 verbose stack at Promise._settlePromise0 (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:614:10) 14 verbose stack at Promise._settlePromises (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:693:18) 14 verbose stack at Promise._fulfill (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:638:18) 14 verbose stack at Promise._settlePromise (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:582:21) 14 verbose stack at Promise._settlePromise0 (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:614:10) 14 verbose stack at Promise._settlePromises (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:693:18) 14 verbose stack at Promise._fulfill (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:638:18) 14 verbose stack at C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\nodeback.js:42:21 15 verbose cwd C:\EasyDoSecureAccess 16 verbose Windows_NT 10.0.10586 17 verbose argv "C:\Program Files\nodejs\node.exe" "C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js" "i" 18 verbose node v8.1.4 19 verbose npm v5.0.3 20 error Unexpected end of JSON input 21 verbose exit [ 1, true ]Phonegap Vue js Android uploading CAMERA image to API server
I'm trying to upload picture taken by Android Camera (cordova-plugin-camera). My code for that is
takePicture () { navigator.camera.getPicture(result => { this.newUnit.addedPic = true this.newUnit.image = result }, error => { alert(error); }, { sourceType : Camera.PictureSourceType.CAMERA, destinationType: Camera.DestinationType.FILE_URI, encodingType: Camera.EncodingType.JPEG, }); },In my this.newUnit.addedPic I got the path like:
file:///storage/emulated/0/Android/data/.../1234.jpgHow can I use it to upload the picture to server from mobile app? In my web part I use FormData to upload the picture.
I was trying to do it by FileTransfer but I get error code 1:
let win = r => {alert(`win`)} let fail = error => { alert("An error has occurred: Code = " + error.code); console.log("upload error source " + error.source); console.log("upload error target " + error.target); } var options = new FileUploadOptions(); options.fileKey = "file"; options.fileName = this.newUnit.image.substr(this.newUnit.image.lastIndexOf('/') + 1); options.mimeType = "image/jpeg"; var params = {}; params.name = "test"; params.creator = 3; options.params = params; var ft = new FileTransfer(); ft.upload(this.newUnit.image, encodeURI("http://myserver/api/v0/units/"), win, fail, options);How can I watch synchronously a state change in vuex?
I am using an opensource vuejs + vuex project and this is the source https://github.com/misterGF/CoPilot/tree/master/src/components
I am currently having problems knowing how to trigger an event from one components to another.
I can use this.$state.store.commit("foo", "bar") to store information in vuex, but when two seperate have two difference export default {} I don't know how I can make the app aware whenever "foo" is for exampled changed to "baz" ... unless I refresh/reload the app, there is no way for me to know the changes
VueJS: Replace/Update Array
I currently have an array of object that I am rendering to a table. I am trying to follow the examples provided by Vuejs to use a "single source of truth" shared between multiple vues on the same page.
Overall, I am trying to make it where when vue1.refresh() is triggered, all the vues update their data when the "single source of truth" is updated. However, self.surveys = surveys; only updates the data on vue1.
// The single source of truth var cache = { data: [{...}] // Array of objects } var vue1 = new Vue({ el: "#table", data: { surveys: cache.data // Points to the single source of truth }, methods: { refresh: function(){ var self = this; // After getting data back from an ajax call .done(function(surveys) { self.surveys = surveys; }); }, } }); var vue2 = new Vue({ el: "#table", data: { surveys: cache.data // Points to the single source of truth }, methods: { // Methods } });Vue.js rounds string output from toFixed?
I have a review that be an int or possible have a decimal. If it is an int I need to display it as 8.0 instead of 8.
Currently my computed method to achieve this looks like this:
reviewAverage() { return Number(this.hotel.cra_average).toFixed(1); }This works fine and when I check my Vue devtools I get this when I am dealing with an int of 8:
reviewAverage:"8.0"Whenever I output the value in my template:
<div class="review">{{ reviewAverage }}</div>I am back to simply seeing 8.
So my computed property works fine but it seems the template resets my string to an int(wtf)?
Is this even possible or is something else going on here?
How to reset a prop value to it's original value in Vuejs
I have a vue component which posts data from a form and it's working fine, however, I need to reset the 'selected' prop to an empty value after submitting the form, how can I do that? Here's the blade.php file :
<form action="{{ url('/cart') }}" method="POST" class="side-by-side reset"> {{ csrf_field() }} {{-- form for my super not working with options vue component --}} <input type="hidden" name="id" v-model="this.id" value="{{ $product->id }}"> <input type="hidden" name="name" v-model="this.name" value="{{ $product->name }}"> <input type="hidden" name="price" v-model="this.price" value="{{ $product->price }}"> @if( ! $product->group->options->isEmpty() ) <select name="options" class="options" v-model="selected" autofocus required> <option value="">Please select one</option> @foreach($product->group->options as $option) <option class="reset" value="{{ $option->name }}">{{ $option->name }}</option> @endforeach </select> @endif <addToCart :product="{{ $product }}" :selected="selected" @submit.prevent="onSubmit()"></addToCart>here's my vue file :
export default { props: ['product', 'selected'], data() { return { id: this.product.id, quantity: 1, name: this.product.name, price: this.product.price, options: this.selected } }, watch: { selected: function() { return this.options = this.selected; //this is initially empty, I want to reset it after form submits } }, methods: { addtocart() { axios.post('/cart/', this.$data) .then(flash(this.product.name + ' was added to cart')) .then( this.resetForm()); },I need to reset the selected prop to it's original empty value, but I get errors, Vuejs doesn't let me modify the prop value directly and I can't figure out how to reset it. Thanks for your help.
Using props to set different text on every page in vue.js
I am using laravel + vue. I want to do title of page in navbar, so when you are in index, in navbar is text index. When you are in settings, navbar says settings etc.
I think props is good for it, but when I use that, it works not good. Look here:
blade.php of index:
@extends('layout.app') @section('content') <index :msg="msg"></index> @endsectionindex.vue:
props: [ 'msg' ],Now navbar:
<template> <nav class="navbar"> <a></a> <p>{{msg}}</p> </nav> </template> <script> export default { props: [ ], data() { return { } }, } </script>and layout:
<body> <div id="app"> <navbar></navbar> @yield('content') </div> </body>How I can change that {{msg}} paragraph in navbar when we are on different pages? My code doesn't work.
[Vue warn]: Property or method "msg" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option.Vue.js 2 + Native PHP - what is the right way to keep user in session?
I have created a small application using Vue.js 2, Axios, native PHP 7.1 (without using php frameworks e.t.c.), MySQL.
I have a login and registration modal windows and some native crud operations with data in my datatable.
I am using Axios to send get/post requests to manage this table and access the database data. This is my login example in Vue:
var loginModal= new Vue ({ el: '#login-modal', data: { ... errors: [], ... userLogin: {action: "", usernameOrEmail: "", password: ""}, ... }, methods: { login: function () { loginModal.userLogin.action = "login"; axios.post("../../route/route.php", JSON.stringify(loginModal.userLogin)) .then(function (response) { loginModal.clearUserLogin(); if (response.data !== "") { console.log(response); if (response.data.error) { loginModal.errors = JSON.parse(response.data.error); } else if (response.data.userId) { header.authenticated = true; loginModal.sessionUserId = response.data.userId; loginModal.modalSuccessMessage = "Success login! Greetings!"; groupManagerModule.sessionUser.userId = response.data.userId; } else { loginModal.modalErrorMessage = "Undefined login error occurs. Try again later."; } } }); },If login is successfull - I am storing some user id in PHP session:
class LoginController { public static function postLogin() { session_start(); $userDao = New UserDaoImpl(); $errorList = array(); $user = FormValidator::validateLogin($errorList, $userDao); if (!empty($errorList)) { $_SESSION['errorList'] = $errorList; echo json_encode(array('error' => json_encode(array_values($errorList)))); } else { $_SESSION['user'] = $user->getId(); echo json_encode(array('userId' => $user->getId())); } }... Everything is working fine. If user is logged in - he can manage some information in this table.
But I am trying to find some right and secure solution to keep user in session even after the browser is closed and I am not sure that my variant is correct (I have begined to create a cookie signs), and after new opening the user must to be in the session and could moderate data.
Question:
What is the best practice for this? (Secure and right way) (cookies, Database token, e.t.c. ?)
(I am newbie in PHP and Vue, sorry for possible dublicate, Thanks!)
materialize modal popup auto initialize not working in vue js
Materialize modal popup is working properly in onclick functions, but not working in mounted() or created()
testingmodel:function(){ $('#firstlogintour').modal('open'); } mounted() { this.testingmodel(); },Do a select list in Vuejs/laravel and databse/axios
I'm currently working on Laravel & Vuejs. I would like to create a select using values from my database: When I select "france" it's supposed to only users from this country.
My users' information shows correctly but it does not react to changes within the select.
my blade.php
<div id ="app"> <select v-model="selected"> <option value="">Country</option> <option value="usa">USA</option> <option value="france">france</option> <option value="uk">United Kingdom</option> <option value="sweden">Sweden</option> </select> <ul> <li v-for="application in applicationsFiltered">@{{ application }}</li> </ul> <apps></apps> </div>my app.js
Vue.component('apps',{ template : ` <table class="users"> <thead> <tr> <th>id</th> <th>OfficialName</th> <th>Country</th> </tr> </thead> <tbody> <tr v-for="app in apps"> <th>{{ app.id }}</th> <th>{{ app.OfficialName }}</th> <th>{{ app.Country }}</th> </tr> </tbody> </table> `, data: function() { return { users: [] } }, created: function() { this.getApps(); }, methods: { getUsers: function(){ axios.get("/users").then((response) => {this.users = response.data}) } }, }), new Vue({ el: '#app', data() { return { selected: '', } }, });I'm new in Vuejs and I don't know how to do my select list / my methods. Do you have any ideas ? :)
Thank you.
JavaScript: Promise on recursion
I got something like this:
methods: { process: function process(id) { this.$http.post('controller/process', { id: id }).then(function (res) { if (res.data.items > 0) { this.process(id); } else { return true; } }, function (data) { this.$notify(data, 'danger'); this.progress = false; }); }, run: function run($id) { this.busy = true; this.process($id); this.busy = false; } },Alright - this is some JavaScript using Vue.js and vue-resource to do am API call (process). The API returns the number of elements to be processed. If this number is > 0, the function should be executed again. This works fine.
Now I would like to solve the following:
Executing the run function should set this.busy = true. After the function process is done processing all items, this.busy should be set to false.
So I read something about promises - but I still don't get how I could use them in this case.
Disable the default in props in production in vue js
Below is my code.
props: { year: { default: 2016, type: Number } }I have used the default value to see the mock but now How can I disable the default value when in production?
Watching in vue cann't work in some case
I used transition in vue by watching current value in vuex making 'alertTip' component to achieve fade-in and fade-out animation,but sometimes it works,sometimes it doesn't work,when value changed and the function in watch dosen't work,the 'tips' cann't disappeared and show all the time.
How to resolve this problem? If there has other method to achieve fade-in and fade-out animation without jQuery
here is the code of the 'alertTip' component:
<template> <transition name="slide-fade"> <div class="info-log" v-if="alertInfo.show"> <img src="../assets/success-icon.png" alt="success-icon" v-if="alertInfo.success"> <img src="../assets/error-icon.png" alt="success-icon" v-else> <span class="info-text">{{alertInfo.alertText}}</span> </div> </transition> </template> <script> import {mapGetters, mapActions} from 'vuex' export default { data () { return { value: '' } }, props: [], mounted () { }, methods: { ...mapActions('global', [ '_ChangeAlertInfo' ]), showTip () { let self = this this.show = !this.show setTimeout(function () { self.show = !self.show }, 1300) } }, computed: { ...mapGetters('global', [ 'alertInfo' ]) }, watch: { 'alertInfo.show': { deep: true, handler (curVal, oldVal) { let self = this setTimeout(function () { self._ChangeAlertInfo({ 'show': false }) }, 1300) } } } } </script> <style lang="less" scoped> .slide-fade-enter-active { transition: all .5s ease; } .slide-fade-leave-active { transition: all .8s cubic-bezier(1.0, 0.5, 0.8, 1.0); } .slide-fade-enter, .slide-fade-leave-active { opacity: 0; } .info-log { position: fixed; top: 40%; left: 50%; z-index: 1111; margin-left: -92px; min-width: 184px; height: 60px; border-radius: 5px; padding-top: 20px; text-align: center; color: #FFF; background-color: rgba(0,0,0,.5); /* IE8 */ filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#7f000000,endColorstr=#7f000000); .info-text { vertical-align: top; } } </style>input field prefilled with vuejs and a reactive character count
As a vuejs component, I want to be able to display a character counter next to my input field. The field is initially set up using a prop (this.initialValue).
When the method this.updateCounter is called the input textfield is blocked : typing into the field won't update its value. If I don't set the maxlength prop, the field is working fine : I can update the textfield.
Usage in a template :
<textfield maxlength="50" name="title" initialValue="Test"></textfield>Here is the component code :
<template> <div class="input"> <div class="input__field"> <span class="input__limit f--small">{{ counter }}</span> <input type="text" :name="name" :maxlength="computedMaxlength" v-model="currentValue" /> </div> </div> </template> <script> export default { name: 'Textfield', props: { name: { default: '' }, maxlength: { default: 0 }, initialValue: { default: '' } }, computed: { hasMaxlength: function () { return this.maxlength > 0; }, computedMaxlength: function () { if(this.hasMaxlength) return this.maxlength; else return false; }, currentValue: { get: function() { return this.initialValue; }, set: function(newValue) { this.updateCounter(newValue); this.$emit("change", newValue); } } }, data: function () { return { counter: 0 } }, methods: { updateCounter: function (newValue) { if(this.maxlength > 0) this.counter = this.maxlength - newValue.length; } }, mounted: function() { this.updateCounter(this.initialValue); } } </script>Why is this array not empty?
I trying to show a message in an array is empty in a filter method in Vue. However, it seems my computed function still returns an array of empty object (If I search for something not there)
What I wish is that it only returns the object that actually has a value - the empty ones should be filtered out?
So if I search for "fjhdsfjsdfjsd" ex, it still return about 200 items, just empty objects, which it shouldnt?
The computed function looks like:
filteredAlarms: function () { let filter = {}; let searchString = this.search_string.toLowerCase(); Object.keys(this.eventLog).forEach(key => { filter[key] = this.eventLog[key].filter(item => { let systemName = item.system_name.toLowerCase(); if(item.type.includes("alarm") && systemName.includes(searchString)) { return item; } }); }); return filter },My POST ajax request returns 302 on a Laravel Controller
I send a POST Ajax request to a Laravel Controller but I get a 302 Found response code.
The controller is the ForgotPasswordController provided by Laravel's Auth package, so nothing special about it.
It has the guest middleware in its constructor and I found that if I remove this middleware from the constructor, the Ajax request works correctly (it returns a 200 response code).
The Ajax request has the X-CSRF-TOKEN and X-XSRF-TOKEN headers, so I don't think there is something missing.
I'm sending this Ajax request from a VueJS password reset form with the Axios library.
Why my POST request does not work if the controller has the guest middleware ?
Thanks !
Here are the headers sent with the request :
POST /password/email HTTP/1.1 Host: myapp.dev Connection: keep-alive Content-Length: 37 Pragma: no-cache Cache-Control: no-cache Origin: http://myapp.dev X-XSRF-TOKEN: eyJpdiI6IjRqTk1yTXFsXC9FVlRzckF0dUM4azdRPT0iLCJ2YWx1ZSI6IjY0MUZzaEpCTXJDcUhzUGhcL2dzYVJmalQrR3pwV3IzYWxiTSt4dVwvN2VVKzJ4b2t3XC9GcVhJcllmK3pQYVV4VGFIZG4wZ0s3NlNCTG01WEl6YzBCY2NRPT0iLCJtYWMiOiIwYmNjOTRiZGJjZTM2YjYyMWJiMzRhNTlkOTkwOWU4Y2M4NmYzYzI5NjhiMTU4MDdiMGJkMmJhYmMwODEzMDhjIn0= X-CSRF-TOKEN: nejsetydvFWgeqppZc5XQtX04b5AdXlsTKSgaydj User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36 Content-Type: application/json;charset=UTF-8 Accept: application/json, text/plain, / X-Requested-With: XMLHttpRequest Referer: http://myapp.dev/password Accept-Encoding: gzip, deflate Accept-Language: fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4 Cookie: XSRF-TOKEN=eyJpdiI6IjRqTk1yTXFsXC9FVlRzckF0dUM4azdRPT0iLCJ2YWx1ZSI6IjY0MUZzaEpCTXJDcUhzUGhcL2dzYVJmalQrR3pwV3IzYWxiTSt4dVwvN2VVKzJ4b2t3XC9GcVhJcllmK3pQYVV4VGFIZG4wZ0s3NlNCTG01WEl6YzBCY2NRPT0iLCJtYWMiOiIwYmNjOTRiZGJjZTM2YjYyMWJiMzRhNTlkOTkwOWU4Y2M4NmYzYzI5NjhiMTU4MDdiMGJkMmJhYmMwODEzMDhjIn0%3D; laravel_session=eyJpdiI6IkJnczRHV3NcLzhLbzZWaUlvTTI2cFlBPT0iLCJ2YWx1ZSI6IkpQYytLXC9pQ1R3MTZlaEx2QWJ4bGpSd21BV25jelJKVDJkQVdcL25GSG4rQkpQc1duZHIrTjErOGt3bk5BVVVcL3FTK1c2XC83Y1NqTmxBaVZ1bkQ2TWV5Zz09IiwibWFjIjoiNzg4Y2UyNWQ0ODcxMWNkNWE3MmU4ZDY1MmIyNTE0NDgwMzFmM2ZjYzkxMzM5ZGM5ZTk5MDI4NjE4OGRkNmJjYyJ9