使用Vue.js,如何创建以componentB作为支柱的componentA,并将其打印在其中?
示例:
index.vue
<template>
<div>
<componentA :componentPlaceHolder="componentB"></componentA>
</div>
</template>
<script>
import componentA from './compnentA.vue';
import componentB from './componentB.vue'
export default {
name: 'index',
components: {componentA,componentB }
}
</script>componentA.vue
<template>
<div>
{{componentPlaceHolder}}
</div>
</template>
<script>
export default {
name: 'componentA',
props: {
'componentPlaceHolder': {}
}
}
</script>发布于 2017-05-14 10:15:46
在你的实施中有一些问题:
componentPlaceHolder位于父作用域,而不是组件A. Read:编译范围中。:is (即v-bind: is)作为动态组件绑定。数据绑定应该引用组件的键。<component-a>来完成的。<component-a>而不是<componentA>,因为HTML元素不区分大小写(<componentA>和<componenta>将被同等对待)。以下是更新的代码:
<template>
<div>
<component-a>
<customComponent :is="componentPlaceHolder"></customComponent>
</component-a>
</div>
</template>
<script>
import componentA from './componentA.vue';
import componentB from './componentB.vue'
export default {
name: 'index',
components: {
'component-a': componentA,
'component-b': componentB
},
data: {
componentPlaceHolder: 'component-b'
}
}
</script>然后在你的componentA.vue
<template>
<div>
<!-- Slot will interweave whatever that is found in <componentA> -->
<slot></slot>
</div>
</template>
<script>
export default {
name: 'componentA'
}
</script>概念证明实例
如果有疑问,这里有一个概念的活生生的例子:
var componentA = {
template: '#component-a'
};
var componentB = {
template: '#component-b'
};
new Vue({
el: '#app',
components: {
'component-a': componentA,
'component-b': componentB
},
data: {
componentPlaceHolder: 'component-b'
}
});<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.3/vue.min.js"></script>
<div id="app">
<component-a>
<!-- DOM elements in here will be interweaved into <slot> -->
<customComponent :is="componentPlaceHolder"></customComponent>
</component-a>
</div>
<template id="component-a">
<div>
<p>I am component A</p>
<slot></slot>
</div>
</template>
<template id="component-b">
<p>I am component B</p>
</template>
脚注:
VueJS自述是异常的,我建议您可以阅读一些与用例非常相关的内容:
https://stackoverflow.com/questions/43962612
复制相似问题