文章目录
- 一、基础计算模板
- 二、计算属性computed
- 三、方法methods
- 四、侦听器watch
- 五、总结
- 六、源码地址
一、基础计算模板
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Vue计算属性、方法、侦听器</title><!--引入vue.js库--><script src="../vue.js"></script>
</head><body>
<div id="root">{{firstName + " " + lastName}}
</div><script>var vm = new Vue({el: '#root',data: {firstName: "gb",lastName: "lfy"}});
</script>
</body>
</html>
升级一下
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Vue计算属性、方法、侦听器</title><!--引入vue.js库--><script src="../vue.js"></script>
</head><body>
<div id="root">{{firstName+" "+lastName}}
</div><script>var vm = new Vue({el: '#root',data: {firstName: "gb",lastName: "lfy"},//计算属性computed: {fallName: function () {return this.firstName + this.lastName;}}});
</script>
</body>
</html>
二、计算属性computed
有缓存机制,会用以前计算的结果
当计算的属性发生变化时会执行一次,当修改的数据不属于计算属性时,会从缓存中查询,不会执行。
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Vue计算属性、方法、侦听器</title><!--引入vue.js库--><script src="../vue.js"></script>
</head><body>
<div id="root">{{fullName}}{{age}}
</div><script>var vm = new Vue({el: '#root',data: {firstName: "gb",lastName: "lfy",age: 22},//计算属性computed: {fullName: function () {console.log("计算了一次")return this.firstName + this.lastName;}}});
</script>
</body>
</html>
三、方法methods
无缓存机制,不管修改什么输入都会执行一次
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Vue计算属性、方法、侦听器</title><!--引入vue.js库--><script src="../vue.js"></script>
</head><body>
<div id="root">{{fullName()}}{{age}}
</div><script>var vm = new Vue({el: '#root',data: {firstName: "gb",lastName: "lfy",age: 22},methods: {fullName: function () {console.log("计算了一次")return this.firstName + this.lastName;}}});
</script>
</body>
</html>
四、侦听器watch
和计算属性一样有缓存机制,只要我侦听的数据不发生改变,我就不会执行
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Vue计算属性、方法、侦听器</title><!--引入vue.js库--><script src="../vue.js"></script>
</head><body>
<div id="root">{{fullName()}}{{age}}
</div><script>var vm = new Vue({el: '#root',data: {firstName: "gb",lastName: "lfy",fullName: "gb lfy",age: 22},watch: {firstName: function () {console.log("计算了一次");this.firstName + this.lastName;},lastName: function () {console.log("计算了一次");this.firstName + this.lastName;},}});
</script>
</body>
</html>
五、总结
如果一个功能既可以用计算属性、方法、侦听器实现,建议优先选择计算属性