使用:
<component :is='动态组件的名称'></component>
例:
//html
<div id="dynamic-component-demo" class="demo">
<button
v-for="tab in tabs"
:key="tab"
:class="['tab-button', {active: currentTab === tab}]"
@click="currentTab = tab"
>
{{tab}}
</button>
<component :is="currentComponent"></component>
</div>
//javascript
Vue.component('tab-home', {
template: `<div>Home component.</div>`
});
Vue.component('tab-posts', {
template: `<div>Posts component.</div>`
});
Vue.component('tab-archive', {
template: `<div>Archive component.</div>`
});
var vm = new Vue({
el: '#app',
data() {
return {
tabs: [
'Home',
'Posts',
'Archive'
],
currentTab: 'Home'
}
},
computed: {
currentComponent() {
return 'tab-' + this.currentTab.toLowerCase();
}
}
});
//css:
.tab-button{
background: #fff;
}
.tab-button.active{
background: red;
}
动态组件 keep-alive的使用:
<keep-alive>
<component :is='currentComponent'></component>
</keep-alive>
ps:
keep-alive 还可以用于:
<keep-alive>
<router-view></router-view>
</keep-alive>
例:
<div id="dynamic-component-demo" class="demo">
<button v-for="tab in tabs"
:key="tab"
:class="['tab-btn', { active: currentTab === tab }]"
@click="currentTab = tab">{{tab}}</button>
<keep-alive>
<component :is="currentComponent"></component>
</keep-alive>
</div>
//js
Vue.component('tab-archive', {
template: '<div>Archive component</div>'
});
Vue.component('tab-posts', {
template: `
<div class="posts-tab">
<ul class="post-sidebar">
<li
v-for="post in posts"
:key="post.id"
:class="['post', {selected: post === selectedPost}]"
@click="selectedPost = post"
>{{post.title}}</li>
</ul>
<div class="selected-post-ctn">
<div v-if="selectedPost">
<h3>{{selectedPost.title}}</h3>
<p v-html="selectedPost.content"></p>
</div>
<strong v-else>Click on a blog to the left to view it.</strong>
</div>
</div>
`,
data() {
return {
posts: [
{
id: 1,
title: 'title1',
content: 'content1'
},{
id: 2,
title: 'title2',
content: 'content2'
},{
id: 3,
title: 'title3',
content: 'content3'
}
],
selectedPost: null
}
}
})
var vm = new Vue({
el: '#app',
data() {
return {
tabs: ['Posts', 'Archive'],
currentTab: 'Posts'
}
},
computed: {
currentComponent() {
return 'tab-' + this.currentTab.toLowerCase();
}
}
});
如果没有加 keep-alive, 每次切换新标签的时候,Vue 都创建了一个新的 currentTabComponent 实例。
可是我们希望那些标签的组件实例能够被在它们第一次被创建的时候缓存下来。
为了解决这个问题,我们可以用一个 <keep-alive> 元素将其动态组件包裹起来
本文介绍Vue中动态组件的使用方法,通过示例展示了如何利用v-bind和v-on实现组件的动态切换,并深入探讨了keep-alive元素在组件缓存中的作用,以提高应用性能。
902

被折叠的 条评论
为什么被折叠?



