Skip to content
Closed
Show file tree
Hide file tree
Changes from all 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
37 changes: 36 additions & 1 deletion packages/runtime-core/__tests__/componentProxy.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import {
createApp,
getCurrentInstance,
nodeOps,
mockWarn
mockWarn,
nextTick
} from '@vue/runtime-test'
import { ComponentInternalInstance } from '../src/component'

Expand Down Expand Up @@ -129,4 +130,38 @@ describe('component: proxy', () => {
expect(instanceProxy.foo).toBe(1)
expect(instance!.user.foo).toBe(1)
})

it('watch', async () => {
const foobar = jest.fn()

const app = createApp()
let instanceProxy: any
const Comp = {
data() {
return {
foo: {
bar: 1,
baz: 2
}
}
},
mounted() {
instanceProxy = this
},
render() {
return null
}
}
app.mount(Comp, nodeOps.createElement('div'))
instanceProxy.$watch('foo.bar', foobar)

instanceProxy.foo.bar++
await nextTick()
expect(foobar).toHaveBeenCalledTimes(1)
expect(foobar.mock.calls[0][0]).toBe(2)

instanceProxy.foo.baz++
await nextTick()
expect(foobar).toHaveBeenCalledTimes(1)
})
})
22 changes: 21 additions & 1 deletion packages/runtime-core/src/apiWatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,24 @@ function doWatch(
}
}

function getValueByPath<T>(
object: any,
path: string,
fallback?: T
): T | undefined {
const pathSegments = path.split('.')

for (let i = 0; i < pathSegments.length; i++) {
if (object[pathSegments[i]]) {
object = object[pathSegments[i]]
} else {
return fallback
}
}

return object
}

// this.$watch
export function instanceWatch(
this: ComponentInternalInstance,
Expand All @@ -211,7 +229,9 @@ export function instanceWatch(
options?: WatchOptions
): StopHandle {
const ctx = this.renderProxy!
const getter = isString(source) ? () => ctx[source] : source.bind(ctx)
const getter = isString(source)
? () => getValueByPath(ctx, source)
: source.bind(ctx)
const stop = watch(getter, cb.bind(ctx), options)
onBeforeUnmount(stop, this)
return stop
Expand Down