问题
I'm trying to understand how to properly watch for some prop variation. I have a parent component (.vue files) that receive data from an ajax call, put the data inside an object and use it to render some child component through a v-for directive, below a simplification of my implementation:
<template>
<div>
<player v-for="(item, key, index) in players"
:item="item"
:index="index"
:key="key"">
</player>
</div>
</template>
... then inside <script>
tag:
data(){
return {
players: {}
},
created(){
let self = this;
this.$http.get('../serv/config/player.php').then((response) => {
let pls = response.body;
for (let p in pls) {
self.$set(self.players, p, pls[p]);
}
});
}
item objects are like this:
item:{
prop: value,
someOtherProp: {
nestedProp: nestedValue,
myArray: [{type: "a", num: 1},{type: "b" num: 6} ...]
},
}
Now, inside my child "player" component I'm trying to watch for any Item's property variation and I use:
...
watch:{
'item.someOtherProp'(newVal){
//to work with changes in "myArray"
},
'item.prop'(newVal){
//to work with changes in prop
}
}
It works but it seems a bit tricky to me and I was wondering if this is the right way to do it. My goal is to perform some action every time prop
changes or myArray
gets new elements or some variation inside existing ones. Any suggestion will be appreciated.
回答1:
You can use a deep watcher for that:
watch: {
item: {
handler(val){
// do stuff
},
deep: true
}
}
This will now detect any changes to the objects in the item
array and additions to the array itself (when used with Vue.set). Here's a JSFiddle: http://jsfiddle.net/je2rw3rs/
EDIT
If you don't want to watch for every change on the top level object, and just want a less awkward syntax for watching nested objects directly, you can simply watch a computed
instead:
var vm = new Vue({
el: '#app',
computed: {
foo() {
return this.item.foo;
}
},
watch: {
foo() {
console.log('Foo Changed!');
}
},
data: {
item: {
foo: 'foo'
}
}
})
Here's the JSFiddle: http://jsfiddle.net/oa07r5fw/
回答2:
Another good approach and one that is a bit more elegant is as follows:
watch:{
'item.someOtherProp': function (newVal, oldVal){
//to work with changes in someOtherProp
},
'item.prop': function(newVal, oldVal){
//to work with changes in prop
}
}
(I learned this approach from @peerbolte in the comment here )
回答3:
VueJs deep watch in child objects
new Vue({
el: "#myElement",
data: {
entity: {
properties: []
}
},
watch: {
'entity.properties': {
handler: function (after, before) {
// Changes detected. Do work...
},
deep: true
}
}
});
回答4:
How if you want to watch a property for a while and then to un-watch it?
Or to watch a library child component property?
You can use the "dynamic watcher":
this.$watch(
'object.property', //what you want to watch
(newVal, oldVal) => {
//execute your code here
}
)
The $watch
returns an unwatch function which will stop watching if it is called.
var unwatch = vm.$watch('a', cb)
// later, teardown the watcher
unwatch()
Also you can use the deep
option:
this.$watch(
'someObject', () => {
//execute your code here
},
{ deep: true }
)
Please make sure to take a look to docs
回答5:
Not seeing it mentioned here, but also possible to use the vue-property-decorator
pattern if you are extending your Vue
class.
import { Watch, Vue } from 'vue-property-decorator';
export default class SomeClass extends Vue {
...
@Watch('item.someOtherProp')
someOtherPropChange(newVal, oldVal) {
// do something
}
...
}
回答6:
My problem with the accepted answer of using deep: true
, is that when deep-watching an array, I can't easily identify which element of the array contains the change. The only clear solution I've found is this answer, which explains how to make a component so you can watch each array element individually.
回答7:
Another way to add that I used to 'hack' this solution was to do this:
I set up a seperate computed
value that would simply return the nested object value.
data : function(){
return {
my_object : {
my_deep_object : {
my_value : "hello world";
}.
},
};
},
computed : {
helper_name : function(){
return this.my_object.my_deep_object.my_value;
},
},
watch : {
helper_name : function(newVal, oldVal){
// do this...
}
}
来源:https://stackoverflow.com/questions/42133894/vue-js-how-to-properly-watch-for-nested-data