通过以下案例对比computed与methods:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<!-- 通过计算属性computed -->
<h2>{{fullName}}</h2>
<h2>{{fullName}}</h2>
<h2>{{fullName}}</h2>
<h2>{{fullName}}</h2>
<!-- 通过方法methods -->
<h2>{{getFullName()}}</h2>
<h2>{{getFullName()}}</h2>
<h2>{{getFullName()}}</h2>
<h2>{{getFullName()}}</h2>
</div>
<script src="../js/vue.js"></script>
<script>
const app = new Vue({
el:'#app',
data:{
firstName:'Lebron',
lastName:'James',
},
computed:{
fullName:function () {
console.log("fullName");
return this.firstName + ' ' + this.lastName;
}
},
methods:{
getFullName(){
console.log("getFullName");
return this.firstName + ' ' + this.lastName;
}
}
})
</script>
</body>
</html>
运行结果如下:
可见:当计算属性computed在使用多次时,只需要调用一次,而methods方法则需要重复调用多次!vue内部会对计算属性进行缓存,当监听到数据发生变化时,才会重新调用。