【问题标题】:Cannot pass parent component's object as prop in Vue after Laravel Mix updateLaravel Mix 更新后无法在 Vue 中将父组件的对象作为道具传递
【发布时间】:2019-12-02 13:24:40
【问题描述】:

我最近将我的项目中的 laravel mix 更新到最新版本,我立即被 Vue 错误所包围。我似乎特别在这个问题上挣扎。我有一个组件:

<template>
    <div>
        <ChildComponent :context="this"></ChildComponent>
    </div>
</template>
<script>
    import ChildComponent from './child-component';
    export default {
        components: { ChildComponent },
        ...
    }
</script>

这是我得到的错误:Error in render: "TypeError: Cannot read property 'context' of undefined"。 看起来很奇怪,因为在 vue-devtools 中,父组件作为对象存在于 ChildComponent 的 context 属性中。 我可能还应该添加上下文在 ChildComponent 的道具中定义为 context: {}

【问题讨论】:

    标签: javascript vue.js laravel-mix


    【解决方案1】:

    this 没有在&lt;template&gt; 中定义,并且试图将整个Vue 实例传递给子进程似乎是一种反模式。您应该显式定义数据和变量并将其传递给子组件,并且(可选)如果您想从子组件接收一些数据,您应该发出事件并绑定到父组件中的这些事件。

    如果您必须从子组件访问父组件,可以在子组件中使用this.$parenthttps://vuejs.org/v2/guide/components-edge-cases.html#Accessing-the-Parent-Component-Instance

    但除非您有充分的理由使用 $parent 变量,否则应避免使用它,因为它将您的组件紧密耦合在一起。

    【讨论】:

    • 我应该补充一点,组件应该紧密耦合在一起吗?无论如何,非常感谢,我知道从这里开始。
    • 规则总有例外,祝一切顺利。
    猜你喜欢
    • 2018-02-12
    • 2021-02-09
    • 2022-01-25
    • 2019-04-03
    • 2020-09-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-10
    • 2019-09-20
    相关资源
    最近更新 更多