Vue父组件向子组件传递一个动态的值,子组件如何保持实时更新实时更新?

原文:https://blog.csdn.net/zhouweixue_vivi/article/details/78550738

 

 

        最近用vue做一个新项目,经历了各种折磨,每次遇到问题都想大喊,格劳资上JQuery,氮素肯定是不行的,今天遇到一个小问题,Vue父组件向子组件传递一个动态的值,子组件只能获取初始值,不能实时更新?

这就有点折磨人了,设想的是,父组件发生变化获取数据,动态传递给子组件,子组件实时刷新视图。vue视图是数据驱动的嘛,这设想就是完美而合理的了吧。可就是不行!!!!

  请教前辈,支个招让用vuex,可就是个小功能能,有点杀鸡用牛刀啊,又去查了查文档,找了找资料。原来需要在子组件watch(监听)父组件数据的变化。

我就这样使用watchl啦,

 
data() {
    return {
        frontPoints: 0
    }
 
},
watch: {
    frontPoints(newValue, oldValue) {
        console.log(newValue)
    }
}        
咦?又出幺蛾子了,完全监听不到嘛!!!

继续查文档,好嘛,原来这种方式只能watch基础类型的变量,我传递的是个object啊,代码,真的处处是坑。。。

为了防止将来继续掉坑,做个总结吧

1、普通watch   

如上所示,用过vue的都应该挺熟悉的

 

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[i] != newValue[i]) {
          console.log(newValue)         }       }     },
    deep:
true   } }
 
3、对象的watch
 
data() {
  return {
    bet: {
      pokerState: 53,
      pokerHistory:
'local'
    } } }, watch: {   bet: {     handler(newValue, oldValue) {
      console.log(newValue)
    },     deep:
true   } }
tips: 只要bet中的属性发生变化(可被监测到的),便会执行handler函数;
如果想监测具体的属性变化,如pokerHistory变化时,才执行handler函数,则可以利用计算属性computed做中间层。
事例如下:

4、对象的具体属性watch(活用computed)

 

data () {
  return {
    bet: {       pokerState:
53,
      pokerHistory:
'local'     } } }, computed: {
  pokerHistory() {
    
return this.bet.pokerHistory   } }, watch: {   pokerHistory(newValue, oldValue) {
    console.log(newValue)
  } }

 

posted @ 2019-01-26 18:07  front-gl  阅读(6300)  评论(0编辑  收藏  举报