这篇文章主要介绍了vue中computed与methods的区别详解,内容还是觉得挺不错的,现在分享给大家,也给大家做个参考。一起过来看看吧
vue中computed可以用来简单的拼接需要展示的数据
computed and methods
拼接展示数据的任务, 也可以用methods完成, 但当页面的数据变化时, methods中的方法会被重新调用(产生不必要的性能消耗), 而methods内的方法只有和自身有关的数据变化时才会被调用
一个简单的实例
computed只在初始化时被调用
computed只在初始化时被调用
methods会在数据变化时被调用, 即使变动的数据与自身无关
测试源码
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>computed的使用</title>
<script src="https://cdn.bootcss.com/vue/2.5.16/vue.js"></script>
</head>
<body>
<p id="root">
</p>
<script>
var vm = new vue({
el: "#root",
data: {
name: "zhaozhao",
age: 13,
hobby: 'python',
nameagestyle: {
fontsize: "20px",
color: "#0c8ac5"
}
},
template: `<p>
<p v-bind:style="nameagestyle">computed方式渲染: {{nameandage}}</p>
<p v-bind:style="nameagestyle">methods 方式渲染: {{getnameandage()}}</p>
<br>
<input type="text" v-model="hobby">
<p>爱好: {{hobby}}</p>
<p>{{nouse()}}</p>
</p>`,
computed: {
nameandage: {
get(){
console.log('调用computed');
return `${this.name} ==> ${this.age}`;
}
}
},
methods: {
getnameandage() {
console.log('调用methods');
return `${this.name} ==> ${this.age}`;
},
nouse(){
console.log("=methods==nouse==");
}
}
})
</script>
</body>
</html>
以上就是vue中computed与methods的区别详解_vue.js的详细内容。