Vue中computed与methods的区别详解
作者:木子昭
这篇文章主要介绍了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>
<div id="root">
</div>
<script>
var vm = new Vue({
el: "#root",
data: {
name: "zhaozhao",
age: 13,
hobby: 'Python',
nameAgeStyle: {
fontSize: "20px",
color: "#0c8ac5"
}
},
template: `<div>
<div v-bind:style="nameAgeStyle">computed方式渲染: {{nameAndAge}}</div>
<div v-bind:style="nameAgeStyle">methods 方式渲染: {{getNameAndAge()}}</div>
<br>
<input type="text" v-model="hobby">
<div>爱好: {{hobby}}</div>
<div>{{noUse()}}</div>
</div>`,
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中的methods、computed计算属性和watch监听属性的使用和区别解析
- vue中的data,computed,methods,created,mounted用法及说明
- Vue中computed属性和watch,methods的区别
- 关于Vue的 watch、computed和methods的区别汇总
- vue.js中methods watch和computed的区别示例详解
- Vue.js计算机属性computed和methods方法详解
- Vue中computed、methods与watch的区别总结
- Vue中的methods、watch、computed的区别
- 深入浅析Vue.js中 computed和methods不同机制
- 浅析Vue中method与computed的区别
- vue中计算属性(computed)、methods和watched之间的区别
- vue中计算属性computed和普通属性method的区别小结
