Vue学习之computed 与 method

前台某个数据是经过计算得出后再渲染在页面上,可以通过vue的computed或 定义method 实现

例如:

 

{{fullName}}

new Vue({
   el:"p",
   data:{
      firstName:"foo",
      lastName:"bar",
     fullName:''
   }
fullName = firstName + lastName,并且后台数据firstName ,lastName发生变化时,前台要实时渲染

computed实现:

computed:{
   getFullName:function()
   {
      return this.firstName+" "+this.lastName 
  }
}
对应前台修改为:

{{getFullName}}


method实现:

methods:{
  getFullName:function(){
   return this.firstName+" " this.lastName
}
}

对应的前台修改为:

{{getFullName()}}


看上去好像没什么区别,我们来看看官网的说法


很清楚,就是用method方法时,不管firstName 和 laseName  有没有发生变化 getFullName 都会执行,如果是用计算属性computed,数据未发生变化时,返回值实际上是上次的缓存,不会重新计算

我们可以试验一下

修改computed代码如下

Vue学习之computed 与 method_第1张图片

控制台:

Vue学习之computed 与 method_第2张图片

控制台只打印了一次 computed 说明getFullName 只计算了一次

再看看methode方式:

Vue学习之computed 与 method_第3张图片

控制台;

Vue学习之computed 与 method_第4张图片

可以看到,methode打印了两次,说明计算了两次

总结: 当某个需要通过逻辑计算得到且在前台多处用到,应该使用vue的computed 

你可能感兴趣的:(vue学习)