Skip to content

Commit

Permalink
feat(runtime-core): allow provide reassignment
Browse files Browse the repository at this point in the history
  • Loading branch information
OnlyWick committed Feb 13, 2024
1 parent 272ab9f commit 441334f
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 3 deletions.
32 changes: 32 additions & 0 deletions packages/runtime-core/__tests__/apiCreateApp.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,38 @@ describe('api: createApp', () => {
expect(`App already provides property with key "bar".`).toHaveBeenWarned()
})

test('allow provide reassignment', () => {
const Root = {
setup() {
provide('foo', 3)
return () => h('div')
},
}

const original = {}
const app = createApp(Root)

app.provide('foo', 1)
app.provide('foo', 2)
expect(`App already provides property with key "foo".`).toHaveBeenWarned()

app.provide('bar', 1)
app.provide('bar', 1)
expect(
`App already provides property with key "bar".`,
).not.toHaveBeenWarned()

app.provide('foo1', original)
app.provide('foo1', original)
expect(
`App already provides property with key "foo1".`,
).not.toHaveBeenWarned()

app.provide('bar1', original)
app.provide('bar1', {})
expect(`App already provides property with key "bar1".`).toHaveBeenWarned()
})

test('runWithContext', () => {
const app = createApp({
setup() {
Expand Down
15 changes: 12 additions & 3 deletions packages/runtime-core/src/apiCreateApp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -373,15 +373,24 @@ export function createAppAPI<HostElement>(
}
},

provide(key, value) {
if (__DEV__ && (key as string | symbol) in context.provides) {
provide(key, newVal) {
const oldValue = context.provides[key as string | symbol]
const isEqual = oldValue === newVal

if (
__DEV__ &&
(key as string | symbol) in context.provides &&
!isEqual
) {
warn(
`App already provides property with key "${String(key)}". ` +
`It will be overwritten with the new value.`,
)
}

context.provides[key as string | symbol] = value
if (!isEqual) {
context.provides[key as string | symbol] = newVal
}

return app
},
Expand Down

0 comments on commit 441334f

Please sign in to comment.