黑马程序员技术交流社区
标题:
【上海校区】Vue父组件向子组件传递一个动态的值,子组...
[打印本页]
作者:
不二晨
时间:
2019-4-15 10:21
标题:
【上海校区】Vue父组件向子组件传递一个动态的值,子组...
场景:父组件发生数据变化,动态的传递给子组件,子组件实时刷新视图
解决方法:需要在子组件watch中(监听)父组件数据的变化
在子组件中使用watch应该注意的问题:
1.watch监听普通类型的数据:
data() {
return {
frontPoints: 0
}
},
watch: {
frontPoints(newValue, oldValue) {
console.log(newValue)
}
}
2.watch监听数组类型 的数据
data() {
return {
winChips: new Array(11).fill(0)
}
},
watch: {
winChips: {
handler(newValue, oldValue) {
for (let i = 0; i < newValue.length; i++) {
if (oldValue
!= newValue
) {
console.log(newValue)
}
}
},
deep: true
}
}
3.watch监听对象类型的数据
data() {
return {
bet: {
pokerState: 53,
pokerHistory: 'local'
}
}
},
watch: {
bet: {
handler(newValue, oldValue) {
console.log(newValue)
},
deep: true
}
}
4.watch监听对象的具体属性:(结合computed)
data() {
return {
bet: {
pokerState: 53,
pokerHistory: 'local'
}
}
},
computed: {
pokerHistory() {
return this.bet.pokerHistory
}
},
watch: {
pokerHistory(newValue, oldValue) {
console.log(newValue)
}
}
tips: 只要bet中的属性发生变化(可被监测到的),便会执行handler函数;
如果想监测具体的属性变化,如pokerHistory变化时,才执行handler函数,则可以利用计算属性computed做中间层。
事例如下:
---------------------
【转载,仅作分享,侵删】
作者:努力_才幸福
原文:
https://blog.csdn.net/weixin_38098192/article/details/80447867
版权声明:本文为博主原创文章,转载请附上博文链接!
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2