交换动态子组件数据

时间:2016-08-11 00:36:51

标签: vue.js vue-component

我是vuejs的新手,我有一个问题,即我有一个父组件,其中有几个子组件使用<component :is="view">进行交换,其中view是父组件的属性。问题是每个子组件都必须填充存储在父组件中的不同数据集...因此

父组件

<template>
 <component :is="view"></component>
</template>
  export default {
   props: ["view"],
   data() { return {data1:[..], data2:[...], ... } }
   components : {
    "view1" : View1,
    "view2" : View2,
    "view3" : View3
   }
}

因此当 view view1 时,请使用 data1 view view2 使用 data2 等......

我可以在子组件的模板中使用一些同步数据吗?

子组件模板

<template>
 <div class="child" v-for"data in data1" :data1="data1">
  {{* data}}
 </div>
</template>

使用 partials 怎么样?我没有看到很多关于它的文档,有人可以详细说明它的使用而不是组件吗?

1 个答案:

答案 0 :(得分:2)

您仍然可以使用道具以正常方式与子组件同步数据。首先,您要在组件定义中定义要接收的道具,即

Vue.component("exclamation-box",{
    template: "#exclamation-box-template",
    props: ['data']
});

然后在动态交换组件时传递此数据,即

<component :is="view.component" :data="view.data"></component>

然后在父组件中,您可以将数据连接到特定视图,例如,将数据放在同一个对象中,例如:

    data: {
        components: {
            view0: {
                component: "question-box",
                data: "View 0"
            },
            view1: {
                component: "question-box",
                data: "View 1"
            },
            view2: {
                component: "exclamation-box",
                data: "View 2"
            },
            view3: {
                component: "question-box",
                data: "View 3"
            }
    },  

然后我使用计算值来确定应该显示哪个视图。

请参阅JSFiddle

相关问题