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

feat: add and delete object attributes would trigger update. #692

Merged
merged 2 commits into from May 19, 2021
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
17 changes: 14 additions & 3 deletions src/utils/instance.ts
@@ -1,7 +1,7 @@
import { ComponentInstance } from '../component'
import vmStateManager from './vmStateManager'
import { setCurrentInstance, getCurrentVue2Instance } from '../runtimeContext'
import { Ref, isRef } from '../apis'
import { Ref, isRef, isReactive } from '../apis'
import { hasOwn, proxy, warn } from './utils'
import { createSlotProxy, resolveSlots } from './helper'

Expand All @@ -20,8 +20,19 @@ export function asVmProperty(
},
})
} else {
// @ts-ignore
vm[propName] = propValue
Object.defineProperty(vm, propName, {
enumerable: true,
configurable: true,
get: () => {
if (isReactive(propValue)) {
;(propValue as any).__ob__.dep.depend()
}
return propValue
},
set: (val) => {
propValue = val
},
})
}

if (__DEV__) {
Expand Down
38 changes: 38 additions & 0 deletions test/setup.spec.js
Expand Up @@ -13,6 +13,8 @@ const {
isReactive,
defineComponent,
onMounted,
set,
del,
} = require('../src')
const { sleep } = require('./helpers/utils')

Expand Down Expand Up @@ -896,6 +898,42 @@ describe('setup', () => {
expect(vm.$el.textContent).toBe('2')
})

// #683 #603 #580
it('should update directly when adding attributes to a reactive object', async () => {
const vm = new Vue({
template: '<div><button @click="add"/>{{ obj.a }}</div>',
setup() {
const obj = reactive({})
const add = () => {
set(obj, 'a', 'new property')
}
return { obj, add }
},
}).$mount()

expect(vm.$el.textContent).toBe('')
await vm.$el.querySelector('button').click()
expect(vm.$el.textContent).toBe('new property')
})

// #683 #603 #580
it('should update directly when deleting attributes from a reactive object', async () => {
const vm = new Vue({
template: '<div><button @click="deleting"/>{{ obj.a }}</div>',
setup() {
const obj = reactive({ a: 'hello' })
const deleting = () => {
del(obj, 'a')
}
return { obj, deleting }
},
}).$mount()

expect(vm.$el.textContent).toBe('hello')
await vm.$el.querySelector('button').click()
expect(vm.$el.textContent).toBe('')
})

// #524
it('should work with reactive arrays.', async () => {
const opts = {
Expand Down