RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:8:30-17:00
你可能遇到了下面的问题
关闭右侧工具栏

新闻中心

这里有您想知道的互联网营销解决方案
Vuecomputed计算属性的使用方法

computed

创新互联建站主营成安网站建设的网络公司,主营网站建设方案,成都App定制开发,成安h5重庆小程序开发搭建,成安网站营销推广欢迎成安等地区企业咨询

computed:相当于method,返回function内return的值赋值在html的DOM上。但是多个{{}}使用了computed,computed内的function也只执行一次。仅当function内涉及到Vue实例绑定的data的值的改变,function才会从新执行,并修改DOM上的内容。

computed和method的对比

{{ message.split('').reverse().join('') }}

这个是vue官网一直拿来作为例子的代码。在{{}}可以很方便的放入单个表达式,但是当一个HTML的DOM里面存在太多的表达式,程序会变得很笨重难于维护。

html

9、method与computed的区别
fullName
{{fullName}}
fullName2
{{fullName}}
fullNameMethod
{{getFullName()}}
fullNameMethod2
{{getFullName()}}

js

var app9 = new Vue({
  el: '#app9',
  data: {
    firstName: 'Foo',
    lastName: 'Bar'
  },
  methods:{
    getFullName:function () {
      console.log("执行了methods")
      return this.firstName+" " +this.lastName;
    }
  },
  computed: {
    fullName: function () {
      console.log("执行了computed")
      return this.firstName + ' ' + this.lastName
    }
  }
})
setTimeout('app9.firstName="Foo2"',3000);

控制台输出的结果

执行了computed
执行了methods
执行了methods
执行了computed
执行了methods
执行了methods 

由此可见使用computed,function只会执行一次。当Vue实例中绑定的data数据改变的时候,computed也相对应的只改变一次。

相同点:在以上代码中,两个p标签都会打印出同样被反转的Hello。

不同点:
使用了methods的:HTML中,每一个调用了Vue的methods的方法,都需要执行一遍reversedMessage()这个方法;
而使用computed计算属性的,只执行一遍将结果保存在缓存中。

computed和watch的对比

html

{{ fullName }}

js

var vm = new Vue({
 el: '#demo',
 data: {
 firstName: 'Foo',
 lastName: 'Bar',
 fullName: 'Foo Bar'
 },
 watch: {
 firstName: function (val) {
  this.fullName = val + ' ' + this.lastName
 },
 lastName: function (val) {
  this.fullName = this.firstName + ' ' + val
 }
 }
})
var vm = new Vue({
 el: '#demo',
 data: {
 firstName: 'Foo',
 lastName: 'Bar'
 },
 computed: {
 fullName: function () {
  return this.firstName + ' ' + this.lastName
 }
 }
})

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持创新互联。


分享文章:Vuecomputed计算属性的使用方法
转载注明:http://scyingshan.cn/article/pcoehj.html