【发布时间】:2018-05-11 14:07:50
【问题描述】:
假设我有一个组件(单文件组件):
// 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 警告]:data() 中的错误:“TypeError:无法读取属性‘吃’的 未定义”
所以看起来this.actionsPredefined 在 Lion.vue 中是未定义的。
这里有选择地将扩展组件(Cat.vue)的actionsPredefined与扩展组件(Lion.vue)的actions合并的正确方法是什么?
在 Lion.vue 中,当我将 actions 从 data 移动到 computed 时,Vue 知道 this.actionsPredefined 是什么,但我无法将其移动到 computed(因为我需要能够更改 @987654333 @ 通过其他方法并更改计算值...显然违背了使用计算值的想法并且不起作用)。
我还可以将Lion.vue 数据中的actions 设置为空,然后仅在created() 钩子中使用predefinedActions 填充它们,它会起作用,但不知何故,它感觉不是正确的方法。
【问题讨论】:
-
我不这么认为——我仍然可以在计算和创建的钩子中访问
this.actionsPredefined。那么在这种情况下正确的做法是什么? -
为什么不直接创建这些方法,然后您可以根据需要覆盖或添加? codepen.io/anon/pen/YLLQKo?editors=1010
-
但 Lions 不能喵喵叫 ;) 通过这种方法,Lion 也继承了
meow,并且只有 Cat 应该拥有meowaction。这就是我需要选择性继承的原因。 -
如果你想挑选方法,我想我根本不会使用扩展,并且会有一组我可以导入的预定义方法。 codesandbox.io/s/r7x9lpln5m
-
方法是在创建Vue实例时绑定到Vue的,所以方法内部的
this会引用Vue(假设方法没有用箭头函数定义,一般是错误的)。查看更新的沙盒。
标签: javascript vue.js vuejs2