vue计算属性
2017-03-02 16:07
471 查看
在模板中绑定表达式是非常便利的,但是它们实际上只用于简单的操作。在模板中放入太多的逻辑会让模板过重且难以维护。例如:
在这种情况下,模板不再简单和清晰。在实现反向显示
这就是为什么任何复杂逻辑,你都应当使用计算属性。
结果:
Original message: "Hello"
Computed reversed message: "olleH"
这里我们声明了一个计算属性
你可以打开浏览器的控制台,修改 vm 。
你可以像绑定普通属性一样在模板中绑定计算属性。 Vue 知道
不经过计算属性,我们可以在 method 中定义一个相同的函数来替代它。对于最终的结果,两种方式确实是相同的。然而,不同的是计算属性是基于它的依赖缓存。计算属性只有在它的相关依赖发生改变时才会重新取值。这就意味着只要
这也同样意味着如下计算属性将不会更新,因为
相比而言,每当重新渲染的时候,method 调用总会执行函数。
我们为什么需要缓存?假设我们有一个重要的计算属性 A ,这个计算属性需要一个巨大的数组遍历和做大量的计算。然后我们可能有其他的计算属性依赖于 A 。如果没有缓存,我们将不可避免的多次执行 A 的 getter !如果你不希望有缓存,请用 method 替代。
上面代码是命令式的和重复的。跟计算属性对比:
这样更好,不是吗?
现在在运行
例如:
在这个示例中,使用
除了
<div id="example"> {{ message.split('').reverse().join('') }} </div>
在这种情况下,模板不再简单和清晰。在实现反向显示
message之前,你应该确认它。这个问题在你不止一次反向显示 message 的时候变得更加糟糕。
这就是为什么任何复杂逻辑,你都应当使用计算属性。
基础例子
<div id="example"> <p>Original message: "{{ message }}"</p> <p>Computed reversed message: "{{ reversedMessage }}"</p> </div>
var vm = new Vue({ el: '#example', data: { message: 'Hello' }, computed: { // a computed getter reversedMessage: function () { // `this` points to the vm instance return this.message.split('').reverse().join('') } } })
结果:
Original message: "Hello"
Computed reversed message: "olleH"
这里我们声明了一个计算属性
reversedMessage。我们提供的函数将用作属性
vm.reversedMessage的 getter 。
console.log(vm.reversedMessage) // -> 'olleH' vm.message = 'Goodbye' console.log(vm.reversedMessage) // -> 'eybdooG'
你可以打开浏览器的控制台,修改 vm 。
vm.reversedMessage的值始终取决于
vm.message的值。
你可以像绑定普通属性一样在模板中绑定计算属性。 Vue 知道
vm.reversedMessage依赖于
vm.message,因此当
vm.message发生改变时,依赖于
vm.reversedMessage的绑定也会更新。而且最妙的是我们是声明式地创建这种依赖关系:计算属性的 getter 是干净无副作用的,因此也是易于测试和理解的。
计算缓存 vs methods
你可能已经注意到我们可以通过调用表达式中的method来达到同样的效果:<p>Reversed message: "{{ reverseMessage() }}"</p>
// in component methods: { reverseMessage: function () { return this.message.split('').reverse().join('') } }
不经过计算属性,我们可以在 method 中定义一个相同的函数来替代它。对于最终的结果,两种方式确实是相同的。然而,不同的是计算属性是基于它的依赖缓存。计算属性只有在它的相关依赖发生改变时才会重新取值。这就意味着只要
message没有发生改变,多次访问
reversedMessage计算属性会立即返回之前的计算结果,而不必再次执行函数。
这也同样意味着如下计算属性将不会更新,因为
Date.now()不是响应式依赖:
computed: { now: function () { return Date.now() } }
相比而言,每当重新渲染的时候,method 调用总会执行函数。
我们为什么需要缓存?假设我们有一个重要的计算属性 A ,这个计算属性需要一个巨大的数组遍历和做大量的计算。然后我们可能有其他的计算属性依赖于 A 。如果没有缓存,我们将不可避免的多次执行 A 的 getter !如果你不希望有缓存,请用 method 替代。
计算属性 vs Watched Property
Vue.js 提供了一个方法$watch,它用于观察 Vue 实例上的数据变动。当一些数据需要根据其它数据变化时,
$watch很诱人 —— 特别是如果你来自 AngularJS 。不过,通常更好的办法是使用计算属性而不是一个命令式的
$watch回调。思考下面例子:
<div id="demo">{{ fullName }}</div>
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 } } })
上面代码是命令式的和重复的。跟计算属性对比:
var vm = new Vue({ el: '#demo', data: { firstName: 'Foo', lastName: 'Bar' }, computed: { fullName: function () { return this.firstName + ' ' + this.lastName } } })
这样更好,不是吗?
计算setter
计算属性默认只有 getter ,不过在需要时你也可以提供一个 setter :// ... computed: { fullName: { // getter get: function () { return this.firstName + ' ' + this.lastName }, // setter set: function (newValue) { var names = newValue.split(' ') this.firstName = names[0] this.lastName = names[names.length - 1] } } } // ...
现在在运行
vm.fullName = 'John Doe'时, setter 会被调用,
vm.firstName和
vm.lastName也会被对应更新。
观察 Watchers
虽然计算属性在大多数情况下更合适,但有时也需要一个自定义的 watcher 。这是为什么 Vue 提供一个更通用的方法通过watch选项,来响应数据的变化。当你想要在数据变化响应时,执行异步操作或开销较大的操作,这是很有用的。
例如:
<div id="watch-example"> <p> Ask a yes/no question: <input v-model="question"> </p> <p>{{ answer }}</p> </div>
<!-- Since there is already a rich ecosystem of ajax libraries --> <!-- and collections of general-purpose utility methods, Vue core --> <!-- is able to remain small by not reinventing them. This also --> <!-- gives you the freedom to just use what you're familiar with. --> <script src="https://unpkg.com/axios@0.12.0/dist/axios.min.js"></script> <script src="https://unpkg.com/lodash@4.13.1/lodash.min.js"></script> <script> var watchExampleVM = new Vue({ el: '#watch-example', data: { question: '', answer: 'I cannot give you an answer until you ask a question!' }, watch: { // 如果 question 发生改变,这个函数就会运行 question: function (newQuestion) { this.answer = 'Waiting for you to stop typing...' this.getAnswer() } }, methods: { // _.debounce 是一个通过 lodash 限制操作频率的函数。 // 在这个例子中,我们希望限制访问yesno.wtf/api的频率 // ajax请求直到用户输入完毕才会发出 // 学习更多关于 _.debounce function (and its cousin // _.throttle), 参考: https://lodash.com/docs#debounce getAnswer: _.debounce( function () { var vm = this if (this.question.indexOf('?') === -1) { vm.answer = 'Questions usually contain a question mark. ;-)' return } vm.answer = 'Thinking...' axios.get('https://yesno.wtf/api') .then(function (response) { vm.answer = _.capitalize(response.data.answer) }) .catch(function (error) { vm.answer = 'Error! Could not reach the API. ' + error }) }, // 这是我们为用户停止输入等待的毫秒数 500 ) } }) </script>
在这个示例中,使用
watch选项允许我们执行异步操作(访问一个 API),限制我们执行该操作的频率,并在我们得到最终结果前,设置中间状态。这是计算属性无法做到的。
除了
watch选项之外,您还可以使用 vm.$watch API 命令。
相关文章推荐
- vue-使用计算属性遇到的坑
- Vue.js笔记-计算属性 class与style绑定
- vue的计算属性(computed)、methods、watched三者区别
- Vue——计算属性
- Vue.js计算属性
- vue计算属性
- VUE 中的计算属性和观察者
- vue的computed计算属性学习
- vue.js(5)-计算属性和观察者
- VUE-计算属性
- 计算属性 vue
- vue的计算属性
- vue.js计算属性和观察者
- Vue 计算属性
- Vue.js的计算属性
- Vue计算属性(computed)、methods、watched三者区别
- vue.js基础知识篇(3):计算属性、表单控件绑定
- vue.js计算属性computed用法实例分析
- 详解vue2.0监听属性的使用心得及搭配计算属性的使用
- vue的过滤器和计算属性