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 provide isn't reactive with a single array, Fix #5223 #5229

Merged
merged 2 commits into from
Mar 21, 2017
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion src/core/instance/inject.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
/* @flow */

import { hasSymbol } from 'core/util/env'
import { warn } from '../util/index'
import { defineReactive } from '../observer/index'

export function initProvide (vm: Component) {
const provide = vm.$options.provide
Expand Down Expand Up @@ -29,7 +31,18 @@ export function initInjections (vm: Component) {
let source = vm
while (source) {
if (source._provided && provideKey in source._provided) {
vm[key] = source._provided[provideKey]
if (process.env.NODE_ENV !== 'production') {
defineReactive(vm, key, source._provided[provideKey], () => {
warn(
`Avoid mutating a injections directly since the value will be ` +
`overwritten whenever the provided component re-renders. ` +
`injections being mutated: "${key}"`,
vm
)
})
} else {
defineReactive(vm, key, source._provided[provideKey])
}
break
}
source = source.$parent
Expand Down
55 changes: 55 additions & 0 deletions test/unit/features/options/inject.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -162,4 +162,59 @@ describe('Options provide/inject', () => {
expect(vm.$el.textContent).toBe('123')
})
}

// Github issue #5223
it('should work with reactive array', done => {
const vm = new Vue({
template: `<div><child></child></div>`,
data () {
return {
foo: []
}
},
provide () {
return {
foo: this.foo
}
},
components: {
child: {
inject: ['foo'],
template: `<span>{{foo.length}}</span>`
}
}
}).$mount()

expect(vm.$el.innerHTML).toEqual(`<span>0</span>`)
vm.foo.push(vm.foo.length)
vm.$nextTick(() => {
expect(vm.$el.innerHTML).toEqual(`<span>1</span>`)
vm.foo.pop()
vm.$nextTick(() => {
expect(vm.$el.innerHTML).toEqual(`<span>0</span>`)
done()
})
})
})

it('should warn when injections has been modified', () => {
const key = 'foo'
const vm = new Vue({
provide: {
foo: 1
}
})

const child = new Vue({
parent: vm,
inject: ['foo']
})

expect(child.foo).toBe(1)
child.foo = 2
expect(
`Avoid mutating a injections directly since the value will be ` +
`overwritten whenever the provided component re-renders. ` +
`injections being mutated: "${key}"`).toHaveBeenWarned()
})
})