zoukankan      html  css  js  c++  java
  • Vue父组件向子组件传递一个动态的值,子组件如何保持实时更新实时更新?

    最近用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)
      }
    }

  • 相关阅读:
    [转载]如何让企业网站发挥出应用的功能?
    [转载]创业流程
    velocity foreach跳出循环
    【转】cgi技术
    webx3 日志系统级别问题
    ibatis主键自增用法
    【转】java内部类总结
    java初始化顺序
    一点一点学习Ubuntu
    jboss 的端口修改
  • 原文地址:https://www.cnblogs.com/zzsdream/p/10211892.html
Copyright © 2011-2022 走看看