【问题标题】:How can I pass data from .js to .vue?如何将数据从 .js 传递到 .vue?
【发布时间】:2019-10-15 17:20:37
【问题描述】:

我正在尝试将数据从其父 .js 文件加载到我的 .vue 组件文件中。

这是我的 .html 文件:

<div class="modal-container">
    <section class="modal">
        <modal-component></modal-component>
    </section>
</div>

这是我的 .js 文件:

var modal = new Vue({
    el: 'section.modal',
    data: {
        msg: 'Hello world!'
    },
    components: {
        'modal-component': httpVueLoader('./templates/test.vue')
    }
});

这是我的 .vue 文件:

<template>
    <section>               
        <p class="test">{{ msg }}</p>
    </section>
</template>

但是,当我加载页面时,控制台中出现此错误,并且“msg”的值为空白:

[Vue warn]: Property or method "msg" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.

【问题讨论】:

  • 你要么需要在modal-component的js文件中定义msg,要么为model-component添加一个prop并绑定msg。您的问题中缺少模型组件的 Javascript 文件。
  • 缺少代码:在&lt;/template&gt;下添加&lt;script&gt; export default { data: () =&gt; { return { msg: "my message" }; } } &lt;/script&gt;

标签: javascript vue.js vuejs2 vue-component vue-loader


【解决方案1】:

这里有两个不同的 Vue 实例。您直接使用new Vue 创建的那个有一个名为msg 的属性。子组件modal-component对应的实例没有。

Vue 中有 3 种主要类型的属性。 datacomputedprops

如果您在 data 的父级上定义了一个属性,那么您可以使用 prop 将其传递给子级。

<modal-component :msg="msg"></modal-component>

在您的.vue 文件中,您需要将msg 定义为一个道具。

props: ['msg']

属性不会自动继承,你总是需要使用 props 来传递它们。

文档:https://vuejs.org/v2/guide/components.html#Passing-Data-to-Child-Components-with-Props

不想搅浑水,使用slot 可能会更好地服务于这个特定示例,但由于它只是一个示例,因此很难确定这是否真的合适。

更新:

完整的文件test.vue 将是:

<template>
    <section>               
        <p class="test">{{ msg }}</p>
    </section>
</template>

<script>
export default {
  name: 'modal-component',
  props: ['msg']
}
</script>

【讨论】:

  • 谢谢!我已经尝试了您的建议——使用道具将正确的传递给孩子——并且 msg 的值('Hello world!')现在附加到 section 元素,如下所示:&lt;section class="modal"&gt;&lt;section msg="Hello world!"&gt;&lt;p&gt;&lt;/p&gt;&lt;/section&gt;&lt;/section&gt;。但是,我的 p 标签仍然是空的。如何在 p 标签中显示 msg 数据?
  • 您似乎没有在孩子身上声明道具。如果没有声明一个 prop,它只会被视为元素上的一个属性。你需要在你的 Vue 文件中有一个合适的 &lt;script&gt; 部分,包括 props: ['msg']
  • 我很抱歉 - 我没有跟上,我有点困惑!能否举个例子说明你的意思?
  • @JamesAnderson 已更新。我建议您阅读vuejs.org/v2/guide/single-file-components.html。您的问题也不清楚您为什么使用httpVueLoader,尽管这并没有改变我的答案。如果您是 Vue 新手,那么我强烈建议您获取 CLI 工具的副本并自动生成框架项目。
猜你喜欢
  • 2021-08-07
  • 2020-07-23
  • 2018-02-23
  • 1970-01-01
  • 2021-09-02
  • 2020-09-25
  • 2017-07-17
  • 2017-12-04
  • 1970-01-01
相关资源
最近更新 更多