Skip to content

Commit

Permalink
feat: add and delete object attributes would trigger update. (#692)
Browse files Browse the repository at this point in the history
  • Loading branch information
ygj6 committed May 19, 2021
1 parent 3485ecb commit 8c27d80
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 3 deletions.
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

0 comments on commit 8c27d80

Please sign in to comment.