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(reactivity): unwrap nested refs on the template #361

Merged
merged 7 commits into from
Jun 10, 2020
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions src/reactivity/unwrap.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { isRef } from './ref';
import { proxy, isFunction, isObject, isArray } from '../utils';
import { isReactive } from './reactive';

export function unwrapRefProxy(value: any) {
if (isFunction(value)) {
return value;
}

if (isRef(value)) {
return value;
}

if (isArray(value)) {
return value;
}

if (isReactive(value)) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if you don't mind answering, I would really be grateful if you take the time

seems to me, that we have a base-case if value is reactive, and we don't recursively unwrap

but on the test-cases it doesn't seem to be the case:
https://github.com/vuejs/composition-api/pull/361/files#diff-ffb3fccc5cc98e58adb1477f88e460b83b048c4b693b3fdb479a559f0c66cb88R484-R490

https://github.com/vuejs/composition-api/pull/361/files#diff-ffb3fccc5cc98e58adb1477f88e460b83b048c4b693b3fdb479a559f0c66cb88R550-R552

asking because i'm running into a reproduction and for a minute i was tricked by a premature understanding of this check

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

reactive has some caveats on Ref Unwrapping

but if a value is reactive, you can safely assume that it's already unwrapping.

This commit is pretty old, some things changed since them

return value;
}

if (!isObject(value)) {
return value;
}

antfu marked this conversation as resolved.
Show resolved Hide resolved
const obj: any = {};

// copy symbols over
Object.getOwnPropertySymbols(value).forEach((s) => (obj[s] = (value as any)[s]));

for (const k of Object.keys(value)) {
const r = value[k];
// if is a ref, create a proxy to retrieve the value,
if (isRef(r)) {
const set = (v: any) => (r.value = v);
const get = () => r.value;

proxy(obj, k, { get, set });
} else {
obj[k] = unwrapRefProxy(r);
}
}

return obj;
}
5 changes: 3 additions & 2 deletions src/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { resolveSlots, createSlotProxy } from './helper';
import { hasOwn, isPlainObject, assert, proxy, warn, isFunction } from './utils';
import { ref } from './apis/state';
import vmStateManager from './vmStateManager';
import { unwrapRefProxy } from './reactivity/unwrap';

function asVmProperty(vm: ComponentInstance, propName: string, propValue: Ref<unknown>) {
const props = vm.$options.props;
Expand Down Expand Up @@ -194,11 +195,11 @@ export function mixin(Vue: VueConstructor) {
bindingValue = ref(bindingValue);
} else {
// bind function to the vm, this will make `this` = vm
if (isFunction(bindingValue)){
if (isFunction(bindingValue)) {
bindingValue = bindingValue.bind(vm);
}
// a non-reactive should not don't get reactivity
bindingValue = ref(markRaw(bindingValue));
bindingValue = ref(markRaw(unwrapRefProxy(bindingValue)));
}
}
asVmProperty(vm, name, bindingValue);
Expand Down
140 changes: 118 additions & 22 deletions test/setup.spec.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const Vue = require('vue/dist/vue.common.js');
const { ref, computed, createElement: h, provide, inject } = require('../src');
const { ref, computed, createElement: h, provide, inject, reactive } = require('../src');

describe('setup', () => {
beforeEach(() => {
Expand Down Expand Up @@ -51,7 +51,7 @@ describe('setup', () => {
expect(vm.b).toBe(1);
});

it('should work with `methods` and `data` options', done => {
it('should work with `methods` and `data` options', (done) => {
let calls = 0;
const vm = new Vue({
template: `<div>{{a}}{{b}}{{c}}</div>`,
Expand Down Expand Up @@ -215,7 +215,7 @@ describe('setup', () => {
expect(vm.$refs.test.b).toBe(1);
});

it('props should not be reactive', done => {
it('props should not be reactive', (done) => {
let calls = 0;
const vm = new Vue({
template: `<child :msg="msg"></child>`,
Expand Down Expand Up @@ -256,7 +256,7 @@ describe('setup', () => {
}).$mount();
});

it('should not make returned non-reactive object reactive', done => {
it('should not make returned non-reactive object reactive', (done) => {
const vm = new Vue({
setup() {
return {
Expand Down Expand Up @@ -285,8 +285,8 @@ describe('setup', () => {
});

it("should put a unenumerable '__ob__' for non-reactive object", () => {
const clone = obj => JSON.parse(JSON.stringify(obj));
const componentSetup = jest.fn(props => {
const clone = (obj) => JSON.parse(JSON.stringify(obj));
const componentSetup = jest.fn((props) => {
const internalOptions = clone(props.options);
return { internalOptions };
});
Expand Down Expand Up @@ -329,7 +329,7 @@ describe('setup', () => {
name: 'child',
props: ['msg'],
setup() {
return props => {
return (props) => {
p = props;
return null;
};
Expand All @@ -340,7 +340,7 @@ describe('setup', () => {
expect(p).toBe(undefined);
});

it('inline render function should work', done => {
it('inline render function should work', (done) => {
// let createElement;
const vm = new Vue({
props: ['msg'],
Expand Down Expand Up @@ -382,45 +382,141 @@ describe('setup', () => {
.then(done);
});

it('should unwrap on the template', () => {
const vm = new Vue({
setup() {
const r = ref('r');
const nested = {
a: ref('a'),
aa: {
b: ref('aa'),
bb: {
cc: ref('aa'),
c: 'aa',
},
},

aaa: reactive({
b: ref('aaa'),
bb: {
c: ref('aaa'),
cc: 'aaa',
},
}),

aaaa: {
b: [1],
bb: ref([1]),
bbb: reactive({
c: [1],
cc: ref([1]),
}),
bbbb: [ref(1)],
},
};
pikax marked this conversation as resolved.
Show resolved Hide resolved

const refList = ref([ref('1'), ref('2'), ref('3')]);
const list = [ref('a'), ref('b')];

return {
r,
nested,
refList,
list,
};
},
template: `<div>
<p id="r">{{r}}</p>
<p id="nested">{{nested.a}}</p>
<p id="list">{{list}}</p>
<p id="refList">{{refList}}</p>

<p id="nested_aa_b">{{ nested.aa.b }}</p>
<p id="nested_aa_bb_c">{{ nested.aa.bb.c }}</p>
<p id="nested_aa_bb_cc">{{ nested.aa.bb.cc }}</p>

<p id="nested_aaa_b">{{ nested.aaa.b }}</p>
<p id="nested_aaa_bb_c">{{ nested.aaa.bb.c }}</p>
<p id="nested_aaa_bb_cc">{{ nested.aaa.bb.cc }}</p>

<p id="nested_aaaa_b">{{ nested.aaaa.b }}</p>
<p id="nested_aaaa_bb_c">{{ nested.aaaa.bb }}</p>
<p id="nested_aaaa_bbb_cc">{{ nested.aaaa.bbb.c }}</p>
<p id="nested_aaaa_bbb_cc">{{ nested.aaaa.bbb.cc }}</p>
Comment on lines +529 to +530
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same id, different ref, and confused with :528 which shouldn't unwrap - the tests for those 3 cases are wrong (overwriting one another)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice catch. Would you mind open a PR? Thanks.

<p id="nested_aaaa_bbbb">{{ nested.aaaa.bbbb }}</p>
</div>`,
}).$mount();

expect(vm.$el.querySelector('#r').textContent).toBe('r');
expect(vm.$el.querySelector('#nested').textContent).toBe('a');

// shouldn't unwrap arrays
expect(JSON.parse(vm.$el.querySelector('#list').textContent)).toMatchObject([
{ value: 'a' },
{ value: 'b' },
]);
expect(JSON.parse(vm.$el.querySelector('#refList').textContent)).toMatchObject([
{ value: '1' },
{ value: '2' },
{ value: '3' },
]);

expect(vm.$el.querySelector('#nested_aa_b').textContent).toBe('aa');
expect(vm.$el.querySelector('#nested_aa_bb_c').textContent).toBe('aa');
expect(vm.$el.querySelector('#nested_aa_bb_cc').textContent).toBe('aa');

expect(vm.$el.querySelector('#nested_aaa_b').textContent).toBe('aaa');
expect(vm.$el.querySelector('#nested_aaa_bb_c').textContent).toBe('aaa');
expect(vm.$el.querySelector('#nested_aaa_bb_cc').textContent).toBe('aaa');

expect(JSON.parse(vm.$el.querySelector('#nested_aaaa_b').textContent)).toMatchObject([1]);
expect(JSON.parse(vm.$el.querySelector('#nested_aaaa_bb_c').textContent)).toMatchObject([1]);
expect(JSON.parse(vm.$el.querySelector('#nested_aaaa_bbb_cc').textContent)).toMatchObject([1]);
expect(JSON.parse(vm.$el.querySelector('#nested_aaaa_bbb_cc').textContent)).toMatchObject([1]);
expect(JSON.parse(vm.$el.querySelector('#nested_aaaa_bbbb').textContent)).toMatchObject([
{ value: 1 },
]);
});

describe('Methods', () => {
it('binds methods when calling with parenthesis', async ()=>{
it('binds methods when calling with parenthesis', async () => {
let context = null;
const contextFunction = jest.fn(function (){
context = this
const contextFunction = jest.fn(function () {
context = this;
});

const vm = new Vue({
template: '<div><button @click="contextFunction()"/></div>',
setup() {
return {
contextFunction
}
}
contextFunction,
};
},
}).$mount();

await vm.$el.querySelector('button').click();
expect(contextFunction).toBeCalled();
expect(context).toBe(vm);
});

it('binds methods when calling without parenthesis', async () => {
let context = null;
const contextFunction = jest.fn(function (){
context = this
const contextFunction = jest.fn(function () {
context = this;
});

const vm = new Vue({
template: '<div><button @click="contextFunction"/></div>',
setup() {
return {
contextFunction
}
}
contextFunction,
};
},
}).$mount();

await vm.$el.querySelector('button').click();
expect(contextFunction).toBeCalled();
expect(context).toBe(vm);
});
})
});
});