asyncComputed 介绍
vue里普通的计算属性computed只能计算一些同步的值,但是如果碰到需要在计算属性中发送一些异步的网络请求,需要用到vue-async-computed异步计算属性的插件
业务场景介绍
结合我们上面讲解的内容,我们需要根据不同的类型查询不同的数据字段,并渲染到组件上面。
因为在计算属性中,需要用到http的请求,此处存在异步操作,如果使用computed则无法渲染,因为computed是同步计算属性。
asyncComputed: {fieldData() {if (this.tableType == "1") {this.findFieldData(store.getters.tableName);}}
asyncComputed 安装与使用
npm install --save vue-async-computed
当使用了 webpack 或者 browserify 等时,需要明确通过 Vue.use 实现安装。
import Vue from 'vue'import AsyncComputed from 'vue-async-computed'Vue.use(AsyncComputed)
和同步计算属性类似,异步计算属性有 get 方法,但是没有 set 方法,设置了也会被忽略。
示例代码:
asyncComputed: {postContent: {get () {return Vue.http.get('/post/' + this.postId).then(response => response.data.postContent)}}}
