关于 Vue 的一些冷门技巧

watch

有时候我们会写一些这样的代码, 在 created 一个组件之后获取数据, 然后根据某个值得变动来获取数据, 正常套路是按照下面写的,

1
2
3
4
5
6
7
8
created() {
this.fetchUserList()
},
watch: {
searchText () {
this.fetchUserList ()
}
}

但是 watch 的 api 其实很复杂, 语法糖甜的掉牙了. 于是我们可以简化为

Vue 异步计算属性实现

前段时间在 GitHub 上看到一个 Vue 异步计算属性的库 - vue-async-computed, 将异步操作转化为计算属性, 例如这样用

1
2
3
4
5
6
7
8
9
10
11
new Vue({
data: {
userId: 1
},
asyncComputed: {
username () {
return Vue.http.get('/get-username-by-id/' + this.userId)
.then(response => response.data.username)
}
}
}

好奇其中原理, 看了源码, 了解其中巧妙的实现思路, 绘制了一张核心思路的原型图.

接下来我们实现一个简(阉)易(割)版本的 vue-async-computed 插件,

趁着 beforeCreatedata 中添加 asyncComputedkey, 使之响应式.

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×