Vue计算属性computed如何使用(computed,vue,编程语言)

时间:2024-05-08 05:27:02 作者 : 石家庄SEO 分类 : 编程语言
  • TAG :

如果你不希望有缓存,请用方法来替代。

计算属性的 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.firstNameapp.lastName也相应地会被更新。如下图所示:

Vue计算属性computed如何使用

观察者

虽然计算属性在大多数情况下更合适,但有时候也需要一个自定义的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的值绑定到组件属性来创建和使用组件中的异步计算属性。

我们可以在项目的根目录下通过yarnnpm来安装vue-async-computed插件:

#Yarn
$yarnaddvue-async-computed

NPM

$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

  • 直到promiseresolve为止,除非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如何使用的详细内容,希望对您有所帮助,信息来源于网络。
上一篇:VUEX getters计算属性如何使用下一篇:

31 人围观 / 0 条评论 ↓快速评论↓

(必须)

(必须,保密)

阿狸1 阿狸2 阿狸3 阿狸4 阿狸5 阿狸6 阿狸7 阿狸8 阿狸9 阿狸10 阿狸11 阿狸12 阿狸13 阿狸14 阿狸15 阿狸16 阿狸17 阿狸18