zoukankan      html  css  js  c++  java
  • 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)
      } }
  • 相关阅读:
    bzoj4152 [AMPPZ2014]The Captain
    bzoj2429 [HAOI2006]聪明的猴子
    bzoj1196 [HNOI2006]公路修建问题
    bzoj1083 [SCOI2005]繁忙的都市
    bzoj1050 [HAOI2006]旅行comf
    bzoj1088 [SCOI2005]扫雷Mine
    bzoj1085 [SCOI2005]骑士精神
    bzoj3437 小P的牧场
    bzoj1296 [SCOI2009]粉刷匠
    A1046 Shortest Distance (20)(20 分)
  • 原文地址:https://www.cnblogs.com/mmzuo-798/p/10324557.html
Copyright © 2011-2022 走看看