Vue动态组件

1,389 阅读1分钟

参考官网写的vue动态组件,希望对你有帮助

结果展示

html部分

<div id="dynamic-component-demo" class="demo">
    <button 
        v-for="(item,index) in tabs" 
        :key="index" :class="['tab-button', { active: currentIndex === index }]"
        @click="currentIndex = index">
        {{ item }}
    </button>
    <component :is="currentTabComponent" class="tab"></component>
</div>

css部分

.tab-button {
    padding: 6px 10px;
    border-top-left-radius: 3px;
    border-top-right-radius: 3px;
    border: 1px solid #ccc;
    cursor: pointer;
    background: #f0f0f0;
    margin-bottom: -1px;
    margin-right: -1px;
}
.tab-button:hover {
    background: #e0e0e0;
}
.tab-button.active {
    background: #e0e0e0;
}
.tab {
    border: 1px solid #ccc;
    padding: 10px;
    width: 122px;
}

js部分

new Vue({
    el: '#dynamic-component-demo',
    data: {
        currentIndex: 0,
        tabs: ['首页', '学院', '招生'],
        status:['One','Two','Three']
    },
    computed: {
        currentTabComponent() {
            return this.status[this.currentIndex]
        }
    },
    components:{
        One:{template: '<div>首页组件</div>'},
        Two:{template: '<div>学院组件</div>'},
        Three:{template: '<div>招生组件</div>'}
    }
})