假设我有一个组件(单个文件组件):
// Cat.vue
export default {
data() {
return {
actionsPredefined: {
eat () => (console.log('eat')),
purr () => (console.log('purr')),
meow () => (console.log('meow')),
}
}
}
}
扩展为:
// Lion.vue
export default {
extends: Cat,
data() {
return {
actions: {
eat: this.actionsPredefined.eat, // is undefined - why?
purr: this.actionsPredefined.purr, // is undefined - why?
roar () => (console.log('roar'))
}
}
}
}
现在,当我使用 Lion.vue 时,我得到:
[Vue warn]: Error in data(): "TypeError: Cannot read property 'eat' of undefined"
看起来像this.actionsPredefined
在 Lion.vue 中未定义。
这里选择性合并的正确方法是什么actionsPredefined
扩展组件 (Cat.vue) 与 actions
扩展组件 (Lion.vue)?
在 Lion.vue 中,当我移动 actions
来自 data
至 computed
Vue 知道什么 this.actionsPredefined
是,但我无法将其移动到 computed
(因为我需要能够通过其他方法更改 actions
并更改计算值……这显然与使用计算值的想法背道而驰,并且行不通)。
我还可以设置 actions
Lion.vue
中为空数据并只用 predefinedActions
填充它们在created()
钩子(Hook),它会起作用,但不知何故,它感觉不是正确的方法。
最佳答案
Vue 调用子组件 (Lion
) 的 data
函数 before 它调用子组件的 data
函数 super 组件(Cat
)。 Cat
中定义的数据属性此时在实例上不可用。
I can also set empty
actions
in Lion.vue data and populate them only increated()
hook and it will work, but somehow it doesn't feel like the right way to do it.
为什么不呢?如果您在 data
Hook 和 created
Hook 中初始化 actions
有什么区别?
关于javascript - 在扩展组件的数据中使用时,扩展组件的数据未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50294217/