Skip to content

Commit e421cb6

Browse files
committed
props: call default value functions with vm as the context (close #1382)
1 parent 2007017 commit e421cb6

File tree

2 files changed

+14
-3
lines changed

2 files changed

+14
-3
lines changed

src/compiler/compile-props.js

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,7 @@ function makePropsLinkFn (props) {
131131
vm._props[path] = prop
132132
if (raw === null) {
133133
// initialize absent prop
134-
_.initProp(vm, prop, getDefault(options))
134+
_.initProp(vm, prop, getDefault(vm, options))
135135
} else if (prop.dynamic) {
136136
// dynamic prop
137137
if (vm._context) {
@@ -174,11 +174,12 @@ function makePropsLinkFn (props) {
174174
/**
175175
* Get the default value of a prop.
176176
*
177+
* @param {Vue} vm
177178
* @param {Object} options
178179
* @return {*}
179180
*/
180181

181-
function getDefault (options) {
182+
function getDefault (vm, options) {
182183
// no default, return undefined
183184
if (!options.hasOwnProperty('default')) {
184185
// absent boolean value defaults to false
@@ -197,6 +198,6 @@ function getDefault (options) {
197198
}
198199
// call factory function for non-Function types
199200
return typeof def === 'function' && options.type !== Function
200-
? def()
201+
? def.call(vm)
201202
: def
202203
}

test/unit/specs/directives/internal/prop_spec.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -496,6 +496,12 @@ if (_.inBrowser) {
496496
prop: {
497497
type: String,
498498
default: 'hello'
499+
},
500+
prop2: {
501+
type: Object,
502+
default: function () {
503+
return { vm: this }
504+
}
499505
}
500506
},
501507
data: function () {
@@ -508,6 +514,10 @@ if (_.inBrowser) {
508514
}
509515
})
510516
expect(vm.$el.textContent).toBe('hello world')
517+
// object/array default value initializers should be
518+
// called with the correct `this` context
519+
var child = vm.$children[0]
520+
expect(child.prop2.vm).toBe(child)
511521
vm.$children[0].prop = 'bye'
512522
_.nextTick(function () {
513523
expect(vm.$el.textContent).toBe('bye world')

0 commit comments

Comments
 (0)