1. 计算属性 用于简单运算的。在模板中放入太多的逻辑会让模板过重且难以维护
计算属性是基于它们的响应式依赖进行缓存的。只在相关响应式依赖发生改变时它们才会重新求值 ( 效率高,节省性能 )
调用方法将总会再次执行函数 ( 效率低、灵活 )
同时,插入方式不一样,计算属性只需插入函数名,方法则需要调用执行。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <div id="example"> <p>Original message: "{{ message }}"</p> <p>Computed reversed message: "{{ reversedMessage() }}"</p> </div> <script src="vue.js"></script> <script> var vm = new Vue({ el: '#example', data: { message: 'Hello' }, // computed: { // // 计算属性的 getter // reversedMessage: function () { // // `this` 指向 vm 实例 // return this.message.split('').reverse().join('') // } // }, methods: { reversedMessage: function () { return this.message.split('').reverse().join('') } } }) </script> </body> </html>View Code
2.侦听器
watch 方法监听
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <div id="demo">{{ fullName }}</div> <script src="vue.js"></script> <script> var vm = new Vue({ el: '#demo', data: { firstName: 'Foo', lastName: 'Bar', fullName: 'Foo Bar' }, watch: { firstName: function (val) { this.fullName = val + ' ' + this.lastName }, lastName: function (val) { this.fullName = this.firstName + ' ' + val } } }) </script> </body> </html>View Code
计算属性 方式监听 ( 简洁、不需要提前定义数据 )
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <div id="demo">{{ fullName }}</div> <script src="vue.js"></script> <script> var vm = new Vue({ el: '#demo', data: { firstName: 'Foo', lastName: 'Bar' }, computed: { fullName: function () { return this.firstName + ' ' + this.lastName } } }) </script> </body> </html>View Code
3. 相关链接