Vue.js的computed和watch用法及区别

1. 如何使用

1.1 computed计算属性

<template>
<div>
  <el-input v-model="value1" placeholder="费用1"></el-input>
  <el-input v-model="value2" placeholder="费用2"></el-input>
  <p>合计: "{{ sum }}"</p>
</div>
</template>

<script>
export default {
    data() {
        return {
            value1:0,
            value2:0,
        }
    },
    computed:{
        sum: function(){
            return this.value1 + this.value2;
        }
    }
}
</script>

这个例子是通过input输入两个数据,并且计算sum显示出来,通过computed计算属性,当input数据改变时,sum也会实时改变。
当然不通过computed也可以,还可以通过method方法实现,不同的是计算属性是基于它们的依赖进行缓存的。计算属性只有在它的相关依赖发生改变时才会重新求值。所以computed比method更优化。

刚刚例子中computed只是get属性,其实它还有set属性,比如下面这样:

<template>
<div>
  <el-input v-model="value1" placeholder="费用1"></el-input>
  <el-input v-model="value2" placeholder="费用2"></el-input>
  <p>合计: "{{ sum }}"</p>
</div>
</template>

<script>
export default {
    data() {
        return {
            value1:0,
            value2:0,
        }
    },
    computed:{
        sum: {
            get: function(){
                return this.value1 + this.value2;
            },
            set: function(value){
                this.value1 = value/2;
                this.value2 = value/2;
            }

        }
    }
}
</script>

1.2 watch观察者

关于watch我们引用官方的一个例子:

<div id="watch-example">
  <p>
    Ask a yes/no question:
    <input v-model="question">
  </p>
  <p>{{ answer }}</p>
</div>
<!-- Since there is already a rich ecosystem of ajax libraries    -->
<!-- and collections of general-purpose utility methods, Vue core -->
<!-- is able to remain small by not reinventing them. This also   -->
<!-- gives you the freedom to just use what you're familiar with. -->
<script src="https://unpkg.com/axios@0.12.0/dist/axios.min.js"></script>
<script src="https://unpkg.com/lodash@4.13.1/lodash.min.js"></script>
<script>
var watchExampleVM = new Vue({
  el: '#watch-example',
  data: {
    question: '',
    answer: 'I cannot give you an answer until you ask a question!'
  },
  watch: {
    // 如果 question 发生改变,这个函数就会运行
    question: function (newQuestion) {
      this.answer = 'Waiting for you to stop typing...'
      this.getAnswer()
    }
  },
  methods: {
    // _.debounce 是一个通过 lodash 限制操作频率的函数。
    // 在这个例子中,我们希望限制访问yesno.wtf/api的频率
    // ajax请求直到用户输入完毕才会发出
    // 学习更多关于 _.debounce function (and its cousin
    // _.throttle), 参考: https://lodash.com/docs#debounce
    getAnswer: _.debounce(
      function () {
        if (this.question.indexOf('?') === -1) {
          this.answer = 'Questions usually contain a question mark. ;-)'
          return
        }
        this.answer = 'Thinking...'
        var vm = this
        axios.get('https://yesno.wtf/api')
          .then(function (response) {
            vm.answer = _.capitalize(response.data.answer)
          })
          .catch(function (error) {
            vm.answer = 'Error! Could not reach the API. ' + error
          })
      },
      // 这是我们为用户停止输入等待的毫秒数
      500
    )
  }
})
</script>

在这个示例中,使用 watch 选项允许我们执行异步操作(访问一个 API),限制我们执行该操作的频率,并在我们得到最终结果前,设置中间状态。这是计算属性无法做到的。

2. 区别和联系

关于watch和computed有什么区别和联系呢,在实际应用中应该怎么使用,是大家比较关系的问题:

  • 应用方面,watch比较适合对状态的监控,比如监控页面一个变量的值改变,需要进行什么操作。而computed适合简单计算并返回结果,结果随着内部变量改变而改变。
  • 调用方面,watch适合比较耗时的操作,比如网络异步请求,一个变量改变触发网络请求。
  • watch可以看做一个onchange事件,computed可以看做几个变量的组合体。
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值