【问题标题】:Loop and bind props to different components循环并将道具绑定到不同的组件
【发布时间】:2017-08-16 20:18:39
【问题描述】:

我有 3 个不同的子组件,它们都需要完全相同的道具和自定义事件侦听器。

Vue.component('parent',{
    template:
        `<div>
            <component1 :prop1="prop1" :prop2="prop2" v-on:some-event="someEventHandler" />
            <component2 :prop1="prop1" :prop2="prop2" v-on:some-event="someEventHandler" />
            <component3 :prop1="prop1" :prop2="prop2" v-on:some-event="someEventHandler" />
        </div>`
})


var testMixin = {
    props:['prop1','prop2'],
    template: `<div>{{prop1}}</div>`
}

Vue.component('component1',{
    mixins:[testMixin]
    ///custom code
})

Vue.component('component2',{
    mixins:[testMixin]
    ///custom code
})

Vue.component('component3',{
    mixins:[testMixin]
    ///custom code
})

有什么办法可以停止在父模板中重复自己?我可以在本地注册组件,然后以某种方式对它们执行v-for 以绑定道具/事件吗?

另外,我应该在哪里声明非反应性数据?

【问题讨论】:

  • 您能否解释一下为什么需要 3 个不同的组件?
  • 它们是显示不同数据集的 d3.js 图,因此我需要每个组件自定义 d3 逻辑来处理数据。子组件都发出我在父组件中处理的相同事件。

标签: vue.js


【解决方案1】:

这样的?使用dynamic components

var testMixin = {
    props:['prop1','prop2'],
    template: `<div>{{prop1}}</div>`
}

const comp1 = Vue.extend({
  mixins:[testMixin],
})
const comp2 = Vue.extend({
  mixins:[testMixin],
})
const comp3 = Vue.extend({
  mixins:[testMixin],
})

Vue.component("parent",{
  template:"<div><component v-for='comp in components' :is='comp' :prop1='prop1' :prop2='prop2'></component>",
  data(){
    return {
      prop1: "prop1",
      prop2: "some other prop",
      components: [comp1, comp2, comp3]
    }
  }
})

Example.

【讨论】:

  • 是的,完全一样。谢谢
猜你喜欢
  • 2018-08-03
  • 1970-01-01
  • 2017-04-14
  • 2021-03-05
  • 2013-12-23
  • 1970-01-01
  • 2019-10-29
  • 2019-12-11
  • 1970-01-01
相关资源
最近更新 更多