Skip to content

Commit 1f07075

Browse files
authoredJun 19, 2020
fix: unwrap refs returned by data (#387)
* fix: unwrap refs returned by `data` * chore: add a new test
1 parent 575d100 commit 1f07075

File tree

2 files changed

+62
-12
lines changed

2 files changed

+62
-12
lines changed
 

‎src/setup.ts

+16-12
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,22 @@ export function mixin(Vue: VueConstructor) {
154154
}
155155
}
156156

157+
const { data } = $options
158+
// wrapper the data option, so we can invoke setup before data get resolved
159+
$options.data = function wrappedData() {
160+
if (setup) {
161+
initSetup(vm, vm.$props)
162+
}
163+
const dataValue =
164+
typeof data === 'function'
165+
? (data as (
166+
this: ComponentInstance,
167+
x: ComponentInstance
168+
) => object).call(vm, vm)
169+
: data || {}
170+
return unwrapRefProxy(dataValue)
171+
}
172+
157173
if (!setup) {
158174
return
159175
}
@@ -166,18 +182,6 @@ export function mixin(Vue: VueConstructor) {
166182
}
167183
return
168184
}
169-
170-
const { data } = $options
171-
// wrapper the data option, so we can invoke setup before data get resolved
172-
$options.data = function wrappedData() {
173-
initSetup(vm, vm.$props)
174-
return typeof data === 'function'
175-
? (data as (
176-
this: ComponentInstance,
177-
x: ComponentInstance
178-
) => object).call(vm, vm)
179-
: data || {}
180-
}
181185
}
182186

183187
function initSetup(vm: ComponentInstance, props: Record<any, any> = {}) {

‎test/setup.spec.js

+46
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,19 @@ describe('setup', () => {
8484
expect(vm.b).toBe(1)
8585
})
8686

87+
// #385
88+
it('should unwrapRef on data', () => {
89+
const vm = new Vue({
90+
data() {
91+
return {
92+
a: ref(1),
93+
}
94+
},
95+
setup() {},
96+
}).$mount()
97+
expect(vm.a).toBe(1)
98+
})
99+
87100
it('should work with `methods` and `data` options', (done) => {
88101
let calls = 0
89102
const vm = new Vue({
@@ -756,4 +769,37 @@ describe('setup', () => {
756769
const vm = new Vue(Constructor).$mount()
757770
expect(vm.$el.textContent).toBe('Composition-api')
758771
})
772+
773+
it('should keep data reactive', async () => {
774+
const vm = new Vue({
775+
template: `<div>
776+
<button id="a" @click="a++">{{a}}</button>
777+
<button id="b" @click="b++">{{b}}</button>
778+
</div>`,
779+
data() {
780+
return {
781+
a: 1,
782+
b: ref(1),
783+
}
784+
},
785+
}).$mount()
786+
787+
const a = vm.$el.querySelector('#a')
788+
const b = vm.$el.querySelector('#b')
789+
790+
expect(a.textContent).toBe('1')
791+
expect(b.textContent).toBe('1')
792+
793+
a.click()
794+
await Vue.nextTick()
795+
796+
expect(a.textContent).toBe('2')
797+
expect(b.textContent).toBe('1')
798+
799+
b.click()
800+
await Vue.nextTick()
801+
802+
expect(a.textContent).toBe('2')
803+
expect(b.textContent).toBe('2')
804+
})
759805
})

0 commit comments

Comments
 (0)
Please sign in to comment.