watch监听对象里面值的变化_Vue构造计算和监听

computed 和 watch 的区别:

computed 计算属性。

不需要加括号,根据依赖是否变化来缓存。

语法:computed :{ [key: string]: Function | { get: Function, set: Function } }

代码示例如下:

import Vue from "vue/dist/vue.js";
new Vue({
  data: {
    user: {
      email: "xxxxx@qq.com",
      nickname: "xxx",
      phone: "138xxxxx"
    }
  },
  computed: {           
    displayName: {
      get() {
        const user = this.user;
        return user.nickname || user.email || user.phone;
      },
      set(value) {
        console.log(value);
        this.user.nickname = value;
      }
    }
  },
  template: `
    <div>
      {{displayName}}
      <div>
      {{displayName}}
      <button @click="add">set</button>
      </div>
    </div>
  `,
  methods: {
    add() {
      console.log("add");
      this.displayName = "圆圆";
    }
  }
}).$mount("#app");

watch 监听侦听。

数据变化的时候执行一个函数,一旦data变化就执行得函数。

语法:watch:{ [key: string]: string | Function | Object | Array }

代码示例如下:

import Vue from "vue/dist/vue.js";
new Vue({
  data: {
    n: 0,
    history: [],
    inUndoMode: false
  },
  watch: {
    n: function(newValue, oldValue) {
      console.log(this.inUndoMode);
      if (!this.inUndoMode) {
        this.history.push({ from: oldValue, to: newValue });
      }
    }
  },
  template: `
    <div>
      {{n}}
      <hr />
      <button @click="add1">+1</button>
      <button @click="add2">+2</button>
      <button @click="minus1">-1</button>
      <button @click="minus2">-2</button>
      <hr/>
      <button @click="undo">撤销</button>
      <hr/>
      {{history}}
    </div>
  `,
  methods: {
    add1() {
      this.n += 1;
    },
    add2() {
      this.n += 2;
    },
    minus1() {
      this.n -= 1;
    },
    minus2() {
      this.n -= 2;
    },
    undo() {
      const last = this.history.pop();
      this.inUndoMode = true;
      console.log("ha" + this.inUndoMode);
      const old = last.from;
      this.n = old;                           // watch n 的函数会异步调用
      this.$nextTick(() => {
        this.inUndoMode = false;
      });
    }
  }
}).$mount("#app");

watch的deep,immediate :

deep深入查看:为了发现对象内部值的变化,可以在选项参数中指定deep: true。 注意监听数组的变更不需要这么做。

immediate第一次渲染是否要执行这个函数:在选项参数中指定immediate: true将立即以表达式的当前值触发回调。

语法:

6467e5bb6b70d33975db8fb9b9db5668.png

deep代码示例如下:

vm.$watch('someObject', callback, {
  deep: true
})
vm.someObject.nestedValue = 123
// callback is fired

immediate代码示例 如下:

vm.$watch('a', callback, {
  immediate: true
})
// 立即以 `a` 的当前值触发回调
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值