Skip to content

Commit

Permalink
fix: unwrap refs returned by data (#387)
Browse files Browse the repository at this point in the history
* fix: unwrap refs returned by `data`

* chore: add a new test
  • Loading branch information
pikax committed Jun 19, 2020
1 parent 575d100 commit 1f07075
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 12 deletions.
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 @@ -84,6 +84,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 @@ -756,4 +769,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')
})
})

0 comments on commit 1f07075

Please sign in to comment.