Skip to content

Commit 9dbe132

Browse files
Allow passing a default value for until the promise resolves for the first time
1 parent 76db21e commit 9dbe132

File tree

2 files changed

+35
-2
lines changed

2 files changed

+35
-2
lines changed

src/index.js

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,11 @@ export default {
1717

1818
Object.keys(this.$options.asyncComputed || {}).forEach(key => {
1919
const fn = this.$options.asyncComputed[key]
20-
this.$options.computed[prefix + key] = fn
21-
newData[key] = null
20+
const get = typeof fn === 'function' ? fn : fn.get,
21+
def = typeof fn.default === 'undefined' ? null : fn.default
22+
23+
this.$options.computed[prefix + key] = get
24+
newData[key] = def
2225
})
2326

2427
this.$options.data = function vueAsyncComputedInjectedDataFn () {

test/index.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -199,3 +199,33 @@ normal computed property objects", t => {
199199
t.equal(vm.c, 'vm-c')
200200
})
201201
})
202+
203+
test("Async computed values can have defaults", t => {
204+
t.plan(6)
205+
const vm = new Vue({
206+
asyncComputed: {
207+
x: {
208+
default: false,
209+
get () {
210+
return Promise.resolve(true)
211+
}
212+
},
213+
y () {
214+
return Promise.resolve(true)
215+
},
216+
z: {
217+
get () {
218+
return Promise.resolve(true)
219+
}
220+
}
221+
}
222+
})
223+
t.equal(vm.x, false, 'x should default to true')
224+
t.equal(vm.y, null, 'y doesn\'t have a default')
225+
t.equal(vm.z, null, 'z doesn\'t have a default despite being defined with an object')
226+
Vue.nextTick(() => {
227+
t.equal(vm.x, true, 'x resolves to true')
228+
t.equal(vm.y, true, 'y resolves to true')
229+
t.equal(vm.z, true, 'z resolves to true')
230+
})
231+
})

0 commit comments

Comments
 (0)