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

场景:父组件发生数据变化,动态的传递给子组件,子组件实时刷新视图数组

解决方法:须要在子组件watch中(监听)父组件数据的变化函数

在子组件中使用watch应该注意的问题:this

1.watch监听普通类型的数据:spa

data() {  
    return {  
        frontPoints: 0      
    }  
},  
watch: {  
    frontPoints(newValue, oldValue) {  
        console.log(newValue)  
    }  
}  


2.watch监听数组类型 的数据code

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  
  }  
}  

4.watch监听对象的具体属性:(结合computed)blog

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作中间层。

ip

相关文章
相关标签/搜索