我有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
绑定道具/事件吗?
另外,我应该在哪里声明非反应数据?
答案 0 :(得分:2)
这样的东西?使用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]
}
}
})