我在试着理解如何正确地观察一些props 变化. 我有一个父组件(.VUE文件),它从Ajax调用接收数据,将数据放在对象中,并使用它通过v-for指令呈现一些子组件,下面是我的实现的简化:
<template>
<div>
<player v-for="(item, key, index) in players"
:item="item"
:index="index"
:key="key"">
</player>
</div>
</template>
... 然后在<script>
标签内:
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:{
prop: value,
someOtherProp: {
nestedProp: nestedValue,
myArray: [{type: "a", num: 1},{type: "b" num: 6} ...]
},
}
现在,在我的子"player"组件中,我试图观察任何项的属性变化,并使用:
...
watch:{
'item.someOtherProp'(newVal){
//to work with changes in "myArray"
},
'item.prop'(newVal){
//to work with changes in prop
}
}
这很管用,但对我来说似乎有点棘手,我想知道这是不是正确的做法.我的目标是在每次prop
个更改或myArray
个获得新元素或现有元素中的一些变化时执行一些操作.如有任何建议,我们将不胜感激.