Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: unwrap refs returned by data #387

Merged
merged 2 commits into from Jun 19, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
28 changes: 16 additions & 12 deletions src/setup.ts
Expand Up @@ -154,6 +154,22 @@ export function mixin(Vue: VueConstructor) {
}
}

const { data } = $options
// wrapper the data option, so we can invoke setup before data get resolved
$options.data = function wrappedData() {
if (setup) {
initSetup(vm, vm.$props)
}
const dataValue =
typeof data === 'function'
? (data as (
this: ComponentInstance,
x: ComponentInstance
) => object).call(vm, vm)
: data || {}
return unwrapRefProxy(dataValue)
}

if (!setup) {
return
}
Expand All @@ -166,18 +182,6 @@ export function mixin(Vue: VueConstructor) {
}
return
}

const { data } = $options
// wrapper the data option, so we can invoke setup before data get resolved
$options.data = function wrappedData() {
initSetup(vm, vm.$props)
return typeof data === 'function'
? (data as (
this: ComponentInstance,
x: ComponentInstance
) => object).call(vm, vm)
: data || {}
}
}

function initSetup(vm: ComponentInstance, props: Record<any, any> = {}) {
Expand Down
46 changes: 46 additions & 0 deletions test/setup.spec.js
Expand Up @@ -83,6 +83,19 @@ describe('setup', () => {
expect(vm.b).toBe(1)
})

// #385
it('should unwrapRef on data', () => {
const vm = new Vue({
data() {
return {
a: ref(1),
}
},
setup() {},
}).$mount()
expect(vm.a).toBe(1)
})

it('should work with `methods` and `data` options', (done) => {
let calls = 0
const vm = new Vue({
Expand Down Expand Up @@ -731,4 +744,37 @@ describe('setup', () => {
const vm = new Vue(Constructor).$mount()
expect(vm.$el.textContent).toBe('Composition-api')
})

it('should keep data reactive', async () => {
const vm = new Vue({
template: `<div>
<button id="a" @click="a++">{{a}}</button>
<button id="b" @click="b++">{{b}}</button>
</div>`,
data() {
return {
a: 1,
b: ref(1),
}
},
}).$mount()

const a = vm.$el.querySelector('#a')
const b = vm.$el.querySelector('#b')

expect(a.textContent).toBe('1')
expect(b.textContent).toBe('1')

a.click()
await Vue.nextTick()

expect(a.textContent).toBe('2')
expect(b.textContent).toBe('1')

b.click()
await Vue.nextTick()

expect(a.textContent).toBe('2')
expect(b.textContent).toBe('2')
})
})