computed计算属性和methods有什么不同

computed:自带缓存机制,数据不发生改变,他就会用之前缓存过的数据
methods:页面的每次渲染都会重新计算
例子1

<template>
  <div>
    {
   
   {fullName}} {
   
   {age}}
    <button @click="age++">点我啊</button>    
  </div>
  
</template>
<script>
export default {
  name:'computed',
  data(){
    return {
      firstName: 'Dell',
      lastName: 'Lee',
      age: 28
    }
  },
  computed:{                                         // 计算属性自带缓存功能,只有它里面的数据发生改变了才会重新计算!
    fullName(){
      console.log("计算了")                                            
      return this.firstName + " " + this.lastName
    }
  }
}
</script>

例子2

<template>
  <div>
    {
   
   {fullName()}} {
   
   {age}}
    <button @click="age++">点我啊</button>    
  </div> 
</template>

<script>
export default {
  name:'computed',
  data(){
    return {
      firstName: 'Dell',
      lastName: 'Lee',
      age: 28
    }
  },
   methods:{                                       // methods只要有数据发生改变了,就会重新计算          
     fullName(){
       console.log("计算了")
       return this.firstName + " " + this.lastName
     }
  }
}
</script>

猜你喜欢

转载自blog.csdn.net/weixin_43906597/article/details/114276462
今日推荐