方法一、<template>
<input type="text" v-model=‘componentName‘>
<button @click=‘add‘>click me to add a component</button>
</template>
<script>
// 引入要添加的所有组件
import component1 from ‘./components/component1.vue‘
import component2 from ‘./components/component2.vue‘
export default {
data: function() {
return {
allComponents: [],
componentName: ‘‘
}
},
components: {
// 注册所有组件
component1,
component2
}
methods: {
add: function() {
this.allComponents.push(this.componentName)
// 重置输入框
this.componentName = ‘‘
},
render: function(h) { // h 为 createElement 函数,接受三个参数
// tag
// data
// children 具体看文档吧
return h(‘div‘,this.allComponents.map(function(componentName) {
return h(componentName)
}))
}
}
}
</script>
方法二、
html
<div id="app">
<button @click="add(‘a-component‘, ‘test‘)">Add A</button>
<button @click="add(‘b-component‘, ‘test‘)">Add B</button>
<ul>
<li :is="item.component" :text="item.text" v-for="item in items"></li>
</ul>
</div>
javascript
var AComponent = Vue.extend({
props: [‘text‘],
template: ‘<li>A Component: {{ text }}</li>‘
})
var BComponent = Vue.extend({
props: [‘text‘],
template: ‘<li>B Component: {{ text }}</li>‘
})
new Vue({
el: ‘#app‘,
components: {
‘a-component‘: AComponent,
‘b-component‘: BComponent,
},
data: {
items: []
},
methods: {
add(component, text) {
this.items.push({
‘component‘: component,
‘text‘: text,
})
}
}
})
方法三、
我是写在父组件中的:
Vue.component(‘mycontent‘, {
props: [‘content‘],
data() {
return {
coms: [],
}
},
render: function(h) {
this.coms = [];
for(var i = 0; i < this.content.length; i++) {
this.coms.push(h(this.content[i], {}))
}
return h(‘div‘, {},
this.coms)
},
});
调用的时候
<mycontent v-bind:content="content"></mycontent>
那么父组件中的content变化时,就会动态加载组件了
时间: 2024-10-11 18:03:19