Vue watcher executed before the new data is bound? - javascript

I am using this code:
var vueApp = new Vue({
el: '#app',
data: {
modalKanji: {}
},
methods: {
showModalKanji(character) {
sendAjax('GET', '/api/Dictionary/GetKanji?character=' + character, function (res) { vueApp.modalKanji = JSON.parse(res); });
}
},
watch: {
'modalKanji': function (newData) {
setTimeout(function () {
uglipop({
class: 'modalKanji', //styling class for Modal
source: 'div',
content: 'divModalKanji'
});
}, 1000);
}
}
});
and I have an element that when clicked on, displays a popup with the kanji data inside:
<span #click="showModalKanji(kebChar)" style="cursor:pointer;>
{{kebChar}}
</span>
<div id="divModalKanji" style='display:none;'>
<div v-if="typeof(modalKanji.Result) !== 'undefined'">
{{ modalKanji.Result.literal }}
</div>
</div>
It works, but only when used with a setTimeout delay to "let the time for Vue to update its model"...if I remove the setTimeout so the code is called instantaneousely in the watch function, the popup data is always "1 iteration behind", it's showing the info of the previous kanji I clicked...
Is there a way for a watcher function to be called AFTER Vue has completed is binding with the new data?

I think you need nextTick, see Async-Update-Queue
watch: {
'modalKanji': function (newData) {
this.$nextTick(function () {
uglipop({
class: 'modalKanji', //styling class for Modal
source: 'div',
content: 'divModalKanji'
});
});
}
}

Related

Vue js. Data fields not binding

I have the following definition for the Vue element:
new Vue({
el: "#app",
data: {
latitude1: 'a',
name: 'aa'
},
mounted() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(position => {
this.latitude1 = position.coords.latitude;
})
} else {
this.latitude1 = "WTF??"
// this doesn't work either:
// this.$nextTick(() => { this.latitude1 = "WTF??" })
}
},
methods: {
// button works... WTF?!?
doIt() {
this.latitude1 = "WTF??"
}
}
});
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.16/dist/vue.js"></script>
<div id="app">
<div>{{ latitude1 }}: {{ name }}</div>
<button #click="doIt">Do it</button>
</div>
I can see the location data being populated. The alert displays the latitude but the 2 way binding for the data field latitude1 is not working.
I have tried storing the object state using this and that also did not work.
My html is as follows:
<div class="form-group" id="app">
<p>
{{latitude1}}
</p>
</div>
One of the things to do inside the Vue.js is to use the defined methods for reactive properties changes.
Here is a code I've provided for it:
function error(err) {
console.warn(`ERROR(${err.code}): ${err.message}`);
}
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
new Vue({
el: "#app",
data: {
latitude1: 'a',
name: 'aa'
},
mounted: function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(position => {
console.log(position.coords.latitude);
Vue.set(this, 'latitude1', position.coords.latitude);
}, error, options)
}
}
});
I also set error handler and options for the navigator query. For following the results please check the console.

Vue.js global event not working

I've got
<component-one></component-one>
<component-two></component-two>
<component-three></component-three>
Component two contains component three.
Currently I emit an event in <component-one> that has to be caught in <component-three>.
In <component-one> I fire the event like this:
this.$bus.$emit('setSecondBanner', finalBanner);
Then in <component-three> I catch it like this:
mounted() {
this.$bus.$on('setSecondBanner', (banner) => {
alert('Caught');
this.banner = banner;
});
},
But the event is never caught!
I define the bus like this (in my core.js):
let eventBus = new Vue();
Object.defineProperties(Vue.prototype, {
$bus: {
get: () => { return eventBus; }
}
});
What could be wrong here? When I check vue-dev-tools I can see that the event has fired!
This is the working example for vue1.
Object.defineProperty(Vue.prototype, '$bus', {
get() {
return this.$root.bus;
}
});
Vue.component('third', {
template: `<div> Third : {{ data }} </div>`,
props:['data']
});
Vue.component('second', {
template: `<div>Second component <third :data="data"></third></div>`,
ready() {
this.$bus.$on('setSecondBanner', (event) => {
this.data = event.data;
});
},
data() {
return {
data: 'Defautl value in second'
}
}
});
Vue.component('first', {
template: `<div>{{ data }}</div>`,
ready() {
setInterval(() => {
this.$bus.$emit('setSecondBanner', {
data: 'Bus sending some data : '+new Date(),
});
}, 1000);
},
data() {
return {
data: 'Defautl value in first'
}
}
});
var bus = new Vue({});
new Vue({
el: '#app',
data: {
bus: bus
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.28/vue.js"></script>
<div id="app">
<second></second>
<first></first>
</div>
Have you tried registering the listener in created instead of mounted?
Also, why define the bus with defineProperties and not simply:
Vue.prototype.$bus = new Vue();

How do I handle click event on the button inside toastr?

I want to handle the button click event inside the toastr. I am using this library: https://www.npmjs.com/package/vue-toastr-2
This is my code:
var app = new Vue({
el: '#app',
data: {
message: 'vue-toastr-2'
},
created: function() {
this.$toastr.success('Click here to fire an event <button #click="clickMe">Hello</button>', 'Title');
},
methods: {
clickMe() {
alert('Clicked');
// write some more code
}
}
})
Basically I want that when clickMe is clicked, my function inside the component should get called. How would I do this?
This is my jsfiddle: https://jsfiddle.net/75154x8w/2/
var app = new Vue({
el: '#app',
data: {
message: 'vue-toastr-2'
},
created: function() {
this.$toastr.success('Click here to fire an event <button onclick="app.clickMe()">Hello</button>', 'Title');
},
methods: {
clickMe() {
alert('Clicked');
}
}
})

Run component method on load vue.js

hey I'm pretty new to Vue.js and I'm trying to accomplish what seems to be a simple thing but I'm, having trouble. Essentially, I need it so every time a component is loaded into the DOM, one of it's methods fire. Here is my current code, I've tried to use v-on:load but it doesn't seem to work.
Vue.component('graph', {
props:['graphId','graphData'],
template: '<canvas v-on:load="{{populateGraph()}}"></canvas>',
methods: {
initGraph: function () {
var settlementBalanceBarChart = new Chart(this.graphId, {
type: "bar",
data: settlementBalanceBarData,
options: settlementBalanceBarOptions
});
},
//this is the function I would like to run
populateGraph: function () {
alert('{{graphId}}');
}
}
});
var vm = new Vue({
el: "#app",
mounted: function(){
}
});
The same code functions fine if I use the v-on:click event
There are instance lifecycle hooks that you can use for that. For example:
Vue.component('graph', {
props:['graphId','graphData'],
template: '<canvas></canvas>',
created: function () {
alert('{{graphId}}');
},
methods: {}
});
You have to call the function prefixed by "this" as following:
var data =
{
cashiers: []
}
var vm = new Vue({
el: '#app',
data: data,
created: function () {
this.getCashiers();
},
methods: {
getCashiers: function () {
vm.cashiers = [];
}
}
});

Vue.js passing functions to props not working

I have a problem that passing functions to components is not working the way it's specified in the documentation.
This is in my app.js
methods: {
updateAnswer: function(question) {
console.log('question: '+question);
}
}
This is in my html-file:
<multiplechoice class="question counterIncrement counterShow active" id="q2" whenanswered="{{ updateAnswer('1') }}"></multiplechoice>
This is in my components.js file:
props: [
'whenanswered'
],
ready: function() {
this.whenanswered();
},
I have already tried this:
props: [
{ name: 'whenanswered', type: Function}
];
but still no luck.
This is in my console when I load the page:
Uncaught TypeError: this.whenanswered is not a function
Any help would be very much appreciated :)
You could do this:
<multiplechoice class="question counterIncrement counterShow active" id="q2" :whenanswered="updateAnswer('1')"></multiplechoice>
Without the ':'(same as v-bind) like you did will only send a string and not evaluate. Even with those {{ }}.
But remember that your updateAnswerfunction should return a function. Since your prop will execute updateAnswer('1') and your multiplechoiceactually expects a function that will be executed when it wants.
methods: {
whenanswered: function(question) { // or whenanswered (question) { for ES6
return function () { ... } // or () => {...} for ES6
}
}
A fiddle would help, but basically, you need:
methods: {
whenanswered: function(question) {
...
}
}
if you wanna call that function. A prop is just a string, not a function.
Example:
<div id="app">
Loading...
<data-table on-load="{{onChildLoaded}}"></data-table>
</div>
new Vue({
el: "#app",
methods: {
onChildLoaded: function (msg) {
console.log(msg);
}
},
components: {
'data-table': {
template: 'Loaded',
props: ['onLoad'],
ready: function () {
this.onLoad('the child has now finished loading!')
}
}
}
});

Categories

Resources