【问题标题】:How to define property with a component?如何用组件定义属性?
【发布时间】:2017-12-30 16:47:30
【问题描述】:

我目前在表单中需要按顺序显示三个步骤,因此我创建了三个组件 - 一个用于流程的每个步骤。

我的 app.js 文件:

import LocationList from './components/LocationList.vue';
import ChooseTime from './components/ChooseTime.vue';
import ChooseMethod from './components/ChooseMethod.vue';

Vue.component('location-list', LocationList);
Vue.component('choose-time', ChooseTime);
Vue.component('choose-method', ChooseMethod);

let store = {
    isVisible: {
        steps: {
            one: true,
            two: false,
            three: false,
        }
    }
};

new Vue({
    el: '#app-order',

    data: store,

    router
});

现在,当我的唯一一条路线被调用时,

从'vue-router'导入VueRouter;

let routes = [
    {
        path: '/order',
        component: require('./views/Order.vue')
    }
];

export default new VueRouter({
    routes
});

所有这些组件都被正确加载。问题是当我尝试一次v-show他们时:

Order.vue:

<template>

    // ...

    <location-list v-show="isVisible.steps.one"></location-list>
    <choose-time v-show="isVisible.steps.two"></choose-time>
    <choose-method v-show="isVisible.steps.three"></choose-method>

    // ...

</template>

<script>
</script>

<style>
</style>

我收到的错误信息是:

[Vue warn]: Property or method "isVisible" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option.

但是当我在 Vue 的浏览器扩展中检查时,isVisible 是在根元素中定义的?

如您所见,它位于根元素中,但不在 Order 视图中。

感谢您的帮助!

【问题讨论】:

  • 步骤组件模板之一中是否引用了isVisible
  • 不,我只有一个基本的文件结构,比如&lt;template&gt;&lt;/template&gt; &lt;script&gt;&lt;/script&gt; &lt;style&gt;&lt;/style&gt;。我没有在其中任何地方引用isVisible
  • 我认为到目前为止发布的内容没有问题。
  • 我愿意,但不幸的是它是私人的。我可以稍后复制这个问题并在回购中分享它,但我只是用一些更详细的信息更新了帖子。我认为问题可能是因为 Order 视图不包含 isVisible 属性,仅包含根父元素。我是 Vue 的新手,对此我深表歉意!
  • 是的,这就是问题所在。您需要将isVisible 向下传递给Order.vue,或者在那里完全定义它。

标签: javascript vue.js


【解决方案1】:

在 Vue 中,子组件无法直接访问其父组件中定义的数据。您必须向下传递数据。

我想如果你只是在Order.vue 中定义了isVisible,你可能会省去一些麻烦。但是,如果您想将其保留在原处,则需要将其传递给组件。

一种简单的方法是将isVisble 定义为Order.vue 的属性,然后将其传递给您的router-view

<router-view :is-visible="isVisible"></router-view>

还有其他方法可以将 props 传递给 defined in the router documentation 的路由。

我说在Order.vue 中定义isVisible 可以省去一些麻烦的原因是,每当您想更改步骤的值时,都需要在根目录下进行,因为您目前已经定义了它.

【讨论】:

  • 我同意,我觉得在组件中定义它会更好。我只是将 isVisible 对象移动到 Order.vue 并将其放在 mount() 方法中?
  • @Chris 只需在组件数据中定义它。 data(){ return { isVisible: ...}}
  • 非常感谢伯特!
猜你喜欢
  • 2012-02-15
  • 1970-01-01
  • 2019-09-08
  • 2011-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-22
相关资源
最近更新 更多