Vue计算属性computed如何使用
导读:本文共3019字符,通常情况下阅读需要10分钟。同时您也可以点击右侧朗读,来听本文内容。按键盘←(左) →(右) 方向键可以翻页。
摘要:如果你不希望有缓存,请用方法来替代。计算属性的 setter计算属性默认只有getter,不过在需要时你也可以提供一个setter:computed:{fullName:{//getterget:function(){returnthis.firstName+''+this.lastName},//setterset:function(newValue){varna... ...
目录
(为您整理了一些要点),点击可以直达。如果你不希望有缓存,请用方法来替代。
计算属性的 setter
计算属性默认只有getter,不过在需要时你也可以提供一个setter:
computed:{
fullName:{
//getter
get:function(){
returnthis.firstName+''+this.lastName
},
//setter
set:function(newValue){
varnames=newValue.split('')
this.firstName=names[0]
this.lastName=names[names.length-1]
}
}
}
效果如下:
你在输入框中输入一个fullName
,然后点击set按钮,可以看到对应的效果。你现在再运行app.fullName="Airen liao"
时,计算属性的setter
会被调用,app.firstName
和app.lastName
也相应地会被更新。如下图所示:
观察者
虽然计算属性在大多数情况下更合适,但有时候也需要一个自定义的watcher
。这是为什么Vue通过watch
选项提供一个更通用的方法,来响应数据的变化。当你想要在数据变化响应时,执行异步操作或开销较大的操作,这是很有用的。
Vue确实提供了一种更通用的方式来观察和响应Vue实例上的数据变动:watch
属性。当你有一些数据需要随着其它数据变动而变动时,你很容易滥用watch
。然而,通常更好的想法是使用计算属性而不是命令式的watch
回调。比如下面的示例:
<divid="app">
{{fullName}}
</div>letapp=newVue({
el:'#app',
data(){
return{
firstName:'Foo',
lastName:'Bar',
fullName:'FooBar'
}
},
watch:{
firstName:function(val){
this.fullName=val+''+this.lastName
},
lastName:function(val){
this.fullName=this.firstName+''+val
}
}
})
上面代码是命令式的和重复的。将它与计算属性的版本进行比较:
letapp=newVue({
el:'#app',
data(){
return{
firstName:'Foo',
lastName:'Bar'
}
},
computed:{
fullName:function(){
returnthis.firstName+''+this.lastName
}
}
})
在Vue中使用异步计算属性
Vue中的计算属性非常好。它们允许你执行复杂的操作或数据格式,同时最大限度地执行依赖项计算的性能,只在依赖更改时更新视图。但遗憾的是,它们完全是同步的。
值得庆幸的是,有一个插件。使用vue-async-computed
包可以通地将一个promise
的值绑定到组件属性来创建和使用组件中的异步计算属性。
我们可以在项目的根目录下通过yarn
或npm
来安装vue-async-computed
插件:
#Yarn
$yarnaddvue-async-computedNPM
$npmivue-async-computed--save
接下来在你的项目中开启这个插件:
//main.js
importVuefrom'vue';
importAsyncComputedfrom'vue-async-computed'
importAppfrom'App.vue';Vue.use(AsyncComputed);
newVue({
el:'#app',
render:h=>h(App)
});
如果你和我一样,对Vue的构建工具不是很熟悉的话,我建议你使用Vue官方提供的构建工具 Vue CLI。默认情况,它提供了五种模板,你可以根据自己喜欢的方式选择自己需要的模板即可。
确认在项目中引用vue-async-computed
之后,咱们就可以开始使用这个插件了。使用如何使用这个插件之前,先来简单的了解一些概念。
在Vue中标准计算属性和异步属性之间有一些区别:
异步属性不能有
setter
直到
promise
的resolve
为止,除非default
被设置,否则该值为null
在大多数情况下,你可以将它们视为返回promise
的计算属性。
<!--MyComponent.vue-->
<template>
<!--在一两秒后myResolvedValue将变成"FancyResolvedValue"-->
<h3>AsynchronousProperty{{myResolvedValue}}</h3>
</template>
<script>
exportdefault{
asyncComputed:{
myResolvedValue(){
returnnewPromise((resolve,reject)=>{
setTimeout(()=>resolve('FancyResolvedValue!'),1000)
})
}
}
}
</script>
使用ES7 / ES2016的async / await
,这将变得更简单:
<!--MyComponent.vue-->这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
<template>
<!--在一两秒后myResolvedValue将变成"FancyResolvedValue"-->
<h3>AsynchronousProperty{{myResolvedValue}}</h3>
</template>
<script>
functionfancinessComesLater(){
returnnewPromise((resolve,reject)=>{
setTimeout(()=>resolve('FancyResolvedValue!'),1000)
})
}
exportdefault{
asyncComputed:{
asyncmyResolvedValue(){
returnawaitfancinessComesLater()
}
}
}
</script>
Vue计算属性computed如何使用的详细内容,希望对您有所帮助,信息来源于网络。