javascript - 在扩展组件的数据中使用时,扩展组件的数据未定义

标签 javascript vue.js vuejs2

假设我有一个组件(单个文件组件):

// 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来自 datacomputed 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 in created() 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/

相关文章:

javascript - z 在 translate3d 中

javascript - Apollo 不可分配给 'VueClass<Vue> 类型的参数

vue.js - VueJS : Why Trigger 'Input' Event Within 'Input' Event Handler?

javascript - 将数据传递到 vuejs 模板

javascript - 使用主干时什么类型的功能在哪里?

javascript - WebAssembly:从 JavaScript 中的参数(带有内存地址)获取字符串的正确方法

javascript - jquery正则表达式替换非数字字符但允许加号

webpack - 在没有 Object.assign 的情况下使用 mapActions 错误?

javascript - 尝试在 Vuejs 中使用 async/await 进行 catch

javascript - Vue - 如何绘制波形