VueJs run watcher handler immediatly after triggering - javascript

Example:
export default {
data() {
return {
data1: 1,
data2: 2
}
},
mounted() {
this.data1 = 2
console.log(this.data2)
},
watch: {
data1: {
handler(newData1) {
this.data2 = newData1 * 3
}
}
}
}
Expected behavior: the browser write number 6 to the console
Current behavior: the browser write number 2 to the console
In this example I try to write the modified data2 after changed data1 value, but it write the data2 value before the watcher handler modify it. Is there a way to immediatly run watcher handler after triggering? I know I can use a computed property in this example but I need data in my project.
I tried to set the watcher immediatly property to true but isn't working.

You can use computed property for data2
export default {
data() {
return {
data1: 1
}
},
mounted() {
this.data1 = 2
console.log(this.data2)
},
computed: {
data2() {
return this.data1 * 3
}
}
}

The watcher will not trigger in the middle of your mounted() handler, you need to wait until the handler has finished. This is how Javascript works, it is not a limitation in Vue.

Current behavior: the browser write number 2 to the console
It becauses Vue performs DOM updates asynchronously first run into mounted you made change to data1 (also puts console.log(this.data2) to callback queue at this point of time this.data2 = 2 thats why you see log 2) it also triggers watch of data1 If you log data2 here you see value of 6.
In order to wait until Vue.js has finished updating the DOM after a data change, you can use Vue.nextTick(callback) immediately after the data is changed
mounted() {
this.data1 = 2
this.$nextTick(() => {
console.log(this.data2); // 6
})
}
or use Vue.$watch - Watch an expression or a computed function on the Vue instance for changes
data() {
return {
data1: 1,
data2: 2
}
},
watch: {
data1: function(val) {
this.data2 = val * 3
}
},
mounted() {
this.data1 = 2
this.$watch('data2', (newVal) => {
console.log(newVal) // 6
})
}

I am not sure what the purpose of your code, but below will work
mounted() {
this.data1 = 2
this.$nextTick(() => {
console.log(this.data2)
})
},

As another answer explains, this is expected default behaviour and can be addressed by using nextTick, most times it's not the case because a computed is used instead, as suggested in yet another answer.
In Vue 3, this can be changed by the use of flush option:
mounted() {
this.data1 = 2
console.log(this.data2) // 6
},
watch: {
data1: {
handler(newData1) {
this.data2 = newData1 * 3
},
flush: 'sync'
}
}

Related

vuetify expansion panel does not update with data change

I have a bunch of expansion panels that are rendered from a list. This list has 60+ items in it, so I have set up a pagination to display 5 results at a time. The problem is that the expansion panels do not correctly update with the new lists. I Know that I am returning a new list.
{{this.viewFilteredTools}}
<success-factors v-for="(x,index) in this.viewFilteredTools" :key="index" :factor="x" :tool="tool" />
{{x}}
</v-expansion-panels>
<v-pagination
v-model="page"
:length="this.paginationLength/5"></v-pagination>
This is just holding the expansion panels which are coming in through <success-factors/>.
<script>
import SuccessFactors from './SuccessFactors.vue';
export default {
components: { SuccessFactors },
props:{
tool:{
type: Object,
required: false,
}
},
data() {
return {
page:1,
paginationLength: 0,
factors: {},
factorsList: [],
filterByItems: [
{text:'A to Z (Complete Reviews First)',value:'ascending'},
{text:'Z to A (Complete Reviews First)',value:'descending'},
{text:'A to Z (all)',value:'allAscending'},
{text:'Z to A (all)',value:'allDescending'}
],
filterValue: {text:'Z to A (all)',value:'allDescending'},
viewFilteredTools:[]
};
},
mounted() {
console.log('something happens here')
this.factorsList = this.tool.factors;
this.paginateResults(1,this.factorsList)
this.paginationLength = this.factorsList.length
},
watch: {
page(oldPage){
this.paginateResults(oldPage,this.factorsList);
}
},
// computed:
async fetch() {
const { $content} = this.$nuxt.context;
this.factors = (await $content(this.tool['factors']).fetch());
this.factorsList = this.tool.factors;
},
methods: {
sortList(lstValue) {
console.log(this.tool.factors);
let sortFactors = this.tool.factors;
sortFactors = sortFactors.sort((a,b) => {
if(a<b){
return -1;
}
if(a>b){
return 1;
}
return 0;
})
this.factors = sortFactors;
},
paginateResults(page,results){
console.log(results)
const startCount = (page-1)*5;
const endCount = startCount + 5;
this.startCount = startCount+1;
this.endCount = endCount;
console.log(results.slice(startCount,endCount))
this.viewFilteredTools = results.slice(startCount,endCount);
}
}
};
</script>
this.viewFilteredTools is created from this.factorsList inside the mount lifecycle. Then any time a new page is chosen it is updated from the method sortList(). I can see the viewFilteredTools does change with every page change due to printing it out above the <success-factors>. However, the <success-factors> does not take the data from the updated lists.
Your best bet is to use a computed property. Vue knows when a computed property is updated & would re-render when that property updates.

Vue.js - watch particular properties of the object and load data on change

I have Vue component with prop named product, it is an object with a bunch of properties. And it changes often.
export default {
props: {
product: {
type: Object,
default: () => {},
},
},
watch: {
'product.p1'() {
this.loadData()
},
'product.p2'() {
this.loadData()
},
},
methods: {
loadData() {
doApiRequest(this.product.p1, this.product.p2)
}
},
}
The component should load new data when only properties p1 and p2 of product are changed.
The one approach is to watch the whole product and load data when it is changed. But it produces unnecessary requests because p1 and p2 may not have changed.
Another idea is to watch product.p1 and product.p2, and call the same function to load data in each watcher.
But it may happen that both p1 and p2 changed in the new version of the product, it would trigger 2 calls.
Will it be a good solution to use a debounced function for data load?
Or rather use single watcher for the whole product and compare new p1 and p2 stringified with their old stringified versions to determine if data loading should be triggered?
There are several approaches to this, each with pros and cons.
One simple approach I do is to use a watch function that accesses each of the properties you want to watch and then returns a new empty object. Vue knows product.p1 and product.p2 were accessed in the watch function, so it will re-execute it any time either of those properties change. Then, by returning a new empty object instance from the watch function, Vue will trigger the watch handler because the watch function returned a new value (and thus what is being watched "changed").
created() {
this.$watch(() => {
// Touch the properties we want to watch
this.product.p1;
this.product.p2;
// Return a new value so Vue calls the handler when
// this function is re-executed
return {};
}, () => {
// p1 or p2 changed
})
}
Pros:
You don't have to stringify anything.
You don't have to debounce the watch handler function.
Cons:
You can't track the previous values of p1 and p2.
Take care if this.product could ever be null/undefined.
It will always trigger when p1 or p2 are changed; even if p1 and p2 are set back to their previous values before the next micro task (i.e. $nextTick()); but this is unlikely to be a problem in most cases.
You need to use this.$watch(). If you want to use the watch option instead then you need to watch a computed property.
Some of these cons apply to other approaches anyway.
A more compact version would be:
this.$watch(
() => (this.product.p1, this.product.p2, {}),
() => {
// changed
}
})
As some of other developers said you can use computed properties to monitor the changing of product.p1 or product.p2 or both of them and then calling loadData() method only once in each case. Here is the code of a hypothetical product.vue component:
<template>
<div>
this is product compo
</div>
</template>
<script>
export default {
name: "product",
watch: {
p1p2: function(newVal, oldVal) {
this.loadData();
}
},
props: {
productProp: {
type: Object,
default: () => {},
},
},
computed: {
p1p2: function() {
return this.productProp.p1 + this.productProp.p2;
}
},
methods: {
loadData() {
console.log("load data method");
}
},
}
</script>
I renamed the prop that it received to productProp and watched for a computed property called p1p2 in that. I supposed that the values of data are in String format (but if they are not you could convert them). Actually p1p2 is the concatenation of productProp.p1 and productProp.p2. So changing one or both of them could fire the loadData() method. Here is the code of a parent component that passes data to product.vue:
<template>
<section>
<product :productProp = "dataObj"></product>
<div class="d-flex justify-space-between mt-4">
<v-btn #click="changeP1()">change p1</v-btn>
<v-btn #click="changeP2()">change p2</v-btn>
<v-btn #click="changeBoth()">change both</v-btn>
<v-btn #click="changeOthers()">change others</v-btn>
</div>
</section>
</template>
<script>
import product from "../components/product";
export default {
name: 'parentCompo',
data () {
return {
dataObj: {
p1: "name1",
p2: "name2",
p3: "name3",
p4: "name4"
}
}
},
components: {
product
},
methods: {
changeP1: function() {
if (this.dataObj.p1 == "name1") {
this.dataObj.p1 = "product1"
} else {
this.dataObj.p1 = "name1"
}
},
changeP2: function() {
if (this.dataObj.p2 == "name2") {
this.dataObj.p2 = "product2"
} else {
this.dataObj.p2 = "name2"
}
},
changeBoth: function() {
if (this.dataObj.p2 == "name2") {
this.dataObj.p2 = "product2"
} else {
this.dataObj.p2 = "name2"
}
if (this.dataObj.p1 == "name1") {
this.dataObj.p1 = "product1"
} else {
this.dataObj.p1 = "name1"
}
},
changeOthers: function() {
if (this.dataObj.p3 == "name3") {
this.dataObj.p3 = "product3"
} else {
this.dataObj.p3 = "name3"
}
}
},
}
</script>
You can test the change buttons to see that by changing dataObj.p1 or dataObj.p2 or both of them the loadData() method only called once and by changing others it is not called.
for you do ontouch event in vuejs while using it with your HTML inline
and you have an object model that house you other variable and you need to validate the any of the variable you will need to put them in watcher and use qoute ('') to tell vuejs that this is from a the model.email
hope this is useful
data() {
return {
model: {},
error_message: [],
}
},
watch: {
'model.EmailAddress'(value) {
// binding this to the data value in the email input
this.model.EmailAddress = value;
this.validateEmail(value);
},
},
methods: {
validateEmail(value) {
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(value)) {
this.error_message['EmailAddress'] = '';
} else {
this.error_message['EmailAddress'] = 'Invalid Email Address';
}
}
},

unexpected side effect vue

I am a newbie in vue.js. I have a problem with side effect in computed property. I'm not sure why i'm getting an unexpected side effect in computer property error with the code below. ESlint shows me this error in console. I found what does it mean, but I dont have any idea how to change. Any ideas?
export default {
name: "Repaid",
components: {
VueSlideBar
},
data() {
return {
response: {},
slider: {
lineHeight: 8,
value: 2000,
data: []
},
days: {},
monthCounts: [5],
currentMonthCount: 5,
isLoading: false,
errorMessage: "",
validationError: ""
};
},
computed: {
finalPrice() {
const index = this.monthCounts.indexOf(this.currentMonthCount);
this.days = Object.keys(this.response.prices)[index]; =>this is my side effect
const payment = this.response.prices[this.days]
[this.slider.value].schedule[0].amount;
}
},
I read that i should add slide() to my variable that.days, to mutate the original object. Or maybe I should carry them to the methodes.
EDIT
I carried all my calculations to methods and trigger a function in computed property.
Now it looks like this:
methods: {
showPeriod() {
const index = this.monthCounts.indexOf(this.currentMonthCount);
this.days = Object.keys(this.response.prices)[index];
const payment = this.response.prices[this.days][this.slider.value]
.schedule[0].amount;
return "R$ " + payment;
},
}
computed: {
finalPrice() {
if (!this.response.prices || this.monthCounts === []) {
return "";
}
return this.showPeriod();
}
},
It's coming from "eslint-plugin-vue" and the link for that rule is below,
https://eslint.vuejs.org/rules/no-side-effects-in-computed-properties.html
Either you override this rule in your eslint rules file or you can simply turn off the eslint for this specific line like below
this.days = Object.keys(this.response.prices)[index]; // eslint-disable-line
--
One more thing (Not related to your question) is that you need to return some value in computed.

How to make sure the function is executed in VueJS

I'm trying to execute 3 functions, and after than console.log the values that they change. I think there should be better approach for this kind of problems, but I'm not sure what it is. What I've done is I went old school, and added loading flag. Basically, loading = 3, when function is loaded, loading--
I'd like to demonstrate my current code (well actually it's not the same, but it will work for demo purposes), so you can get the feeling:
data:() => ({
loading: 3,
first: null,
second: null,
third: null
}),
methods: {
first() {
this.$route.get('/data/for/first').then(response => {
this.first = response.data;
this.loading--;
})
},
second() {
this.$route.get('/data/for/second').then(response => {
this.second = response.data;
this.loading--;
})
},
third() {
this.$route.get('/data/for/third/a').then(responseA => {
let thirdA = responseA.data;
this.$route.get('/data/for/third/b').then(responseB => {
let thirdB = responseB.data;
if (thirdA === thirdB) {
this.third = true;
}
this.loading--;
})
})
},
fireFunctions() {
this.first();
this.second();
this.third();
}
},
watch: {
loading: function() {
if (this.loading === 0) {
console.log(this.first, this.second, this.third)
}
}
}
The output looks like this:
dataForFirst, dataForSecond, dataForThird;
But, if I don't use the watcher, and load this.fireFunctions() in mounted() i get:
dataForFirst, dataForSecond, undefined;
Now, as I understand, this is happening because this.third() needs more time to process the data. As you can see in the code, I added loading flag. So, fire functions will only execute when all of the functions are loaded.
I don't think this is the best approach, so I'd like to hear your opinion on this one.
How would you handle it?
Use Promise.all to wait on all your async functions to return and then run whatever code you need to afterward, example:
methods: {
async all() {
let [first, second, third] = await Promise.all([
this.$route.get('/data/for/first'),
this.$route.get('/data/for/second'),
this.$route.get('/data/for/third')
]);
this.first = first;
this.second = second;
this.third = third;
console.log(first, second, third);
}
}

Polymer 3 lit-element: Array Object changes not picked up by requestRender

I have an object as below. Now when I change a property and call requestRender it won't trigger. As far as I see it, the property change is not detected. How can I achieve this?
static get properties() {
return {
items: Object
}
}
constructor() {
super();
this.items = {
list: [{ a: 5, b: 6 },{ a: 5, b: 6 }]
}
}
onClick() {
this.items.list[1].a = 10; //change property
requestRender(); //doesn't pick up the change...
}
lit-element requires you to manage your properties immutably, so to update that data point, something like the following will be required:
onClick() {
let list = this.items.list.slice();
let item = Object.assign({}, list[1]);
item.a = 10;
list[1] = item;
this.items = {
list: list
};
// will update on it's own with out a render request
}
The above is a very complete, but ES5(ish) answer to this problem. It's also possible to do this with more modern JS that would make this much more manageable.
onClick() {
this.items.list[1].a = 10;
this.items = {
...this.items
};
// will update on it's own with out a render request
}
Hope that helps.

Categories

Resources