Vue计算属性的学习笔记

本文为大家分享了Vue计算属性的学习笔记,供大家参考,具体内容如下

①模板内的表达式实际上只用于简单的运算,对于复杂逻辑,使用计算机属性

②基础例子:

rush:xhtml;">
Original message:"{{message}}"

Computed reversed message:"{{reversedMessage}}"

rush:js;"> 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('') } } })

这里我们声明了一个计算机属性reversedMessage,我们提供的函数将用作属性vm.reversedMessage的getter。

③计算机缓存 vs Methods

可以通过调用表达式中的method来达到同样的效果

rush:xhtml;">

Reversed message:"{{reversedMessage}}"

rush:js;"> //in component methods:{ reversedMessage:function(){ return this.message.split('').reverse()/join('') } }

可以将同一个函数定义为一个method而不是一个计算机属性。对于最终的结果,两种方式确实是相同的。然而不同的计算机属性是基于它们的依赖进行缓存的。计算属性只有在它的相关依赖发生改变时才会重新求值,这就意味着只要message还没有改变,多次访问reversedMessage计算属性会立即返回之前的计算结果,而不必再次执行函数。 下面的计算属性将不再更新,因为Date.Now()不是响应式依赖:

rush:js;"> computed:{ Now:function(){ return Date.Now() } }

只要发生重新渲染,method调用总会执行该函数

④computed属性 vs watch属性

rush:xhtml;">

watch:

rush:js;"> 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 } } })

computed:

rush:js;"> var vm = new Vue({ el:'#demo',data:{ firstName:'Foo',lastName:'Bar' },computed:{ fullName:function(){ return this.firstName + ' ' + this.lastName } } })

⑤计算setter:

计算属性认只有getter,不过在需要是可以提供一个setter:

rush:js;"> // ... 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

当想要在数据变化相应时,执行异步操作或开销较大的操作,这是很有用的。

rush:xhtml;">
Ask a yes/no question:

{{ answer }}

rush:xhtml;">

在这个示例中,使用watch选项允许我们执行异步操作,限制我们执行该操作的频率,并在得到最终结果前,设置中间状态,这是计算属性无法做到的。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程之家。

相关文章

可以通过min-width属性来设置el-table-column的最小宽度。以...
yarn dev,当文件变动后,会自动重启。 yanr start不会自动重...
ref 用于创建一个对值的响应式引用。这个值可以是原始值(如...
通过修改 getWK005 函数来实现这一点。这里的 query 参数就是...
<el-form-item label="入库类型" ...
API 变动 样式类名变化: 一些组件的样式类名有所变动,可能需...