Vue2.x dynamic components
Introduce: It's a page about dynamic components. This example comes from the Vue official guide.
Content
Experience
1. create the dynamic components
We'd better create the dynamic components firstly to avoid omitting.
Vue.component('..', {..})
2. create index in father component(vm)
It includes two index: the whole index array(tabs) & the current index(currentTab)
let vm = new Vue({
el: '#app',
data: {
currentTag: 'comA',
tags:['A', 'B', 'C']
},
})
3. set the trigger in html
The trigger is usually set with v-for and index array.
Also, set a trigger event, such as @click.
The trigger event handle the change of the current index
<button
v-for="tag in tags"
:key="tag"
@click="currentTag = 'com' + tag">{{ tag }}
</button>
4. set the dynamic component in html
The dynamic component should bind the current index by :is=""
<component :is="currentTag"></component>
code
<script src="https://unpkg.com/vue"></script>
<div id="app">
<button
v-for="tab in tabs"
:key="tab"
@click="currentTab = 'com' + tab">{{ tab }}</button>
<component :is="currentTab"></component>
</div>
Vue.component('comA', {
template:`<div>A</div>`
})
Vue.component('comB', {
template:`<div>B</div>`
})
Vue.component('comC', {
template:`<div>C</div>`
})
let vm = new Vue({
el: '#app',
data: {
currentTab: 'comA',
tabs:['A', 'B', 'C']
},
})

浙公网安备 33010602011771号