先看效果:
两种方法:
1、使用v-show来实现组件切换
<button @click="flag=!flag">{{flag?"列表":"表格"}}</button>
<showtable :list="list" v-show="flag">
</showtable>
<showlist :list="list" v-show="!flag">
</showlist>
//利用v-show的显示隐藏来实现列表和表格之间的切换
//列表和表格的模板定义
<template id="showtable">
<table>
<tr>
<td>编号</td>
<td>姓名</td>
<td>年龄</td>
<td>性别</td>
</tr>
<tr v-for="(item,index) in list" :key="index">
<td>{{index+1}}</td>
<td>{{item.name}}</td>
<td>{{item.age}}</td>
<td>{{item.sex}}</td>
</tr>
</table>
</template>
<template id="showlist">
<ul>
<li v-for="(item,index) in list" :key="index">
<p>{{index+1}}</p>
<p v-for="(items,value,i) in item" :key="i">{{items}}</p>
</li>
</ul>
</template>
2、利用component来实现足间切换
<select v-model="currentCpt">
<option value="showtable">表格</option>
<option value="showlist">列表</option>
</select>
<keep-alive>
<!-- 失活的组件将会被缓存! 下一次失活组件重新激活的时候 会直接调用缓存 性能优化 -->
<component :is="currentCpt" :list="list"></component>
</keep-alive>
<script>
Vue.component("showtable", {
template: "#showtable",
props: {
list: Array
}
})
Vue.component("showlist", {
template: "#showlist",
props: {
list: Array
}
})
const vm = new Vue({
el: "#box",
data: {
title: "组件切换",
list: [{
name: "张三",
age: 18,
sex: "男"
},
{
name: "李四",
age: 28,
sex: "男"
},
{
name: "王五",
age: 38,
sex: "男"
},
{
name: "赵六",
age: 48,
sex: "男"
},
],
flag: true,
currentCpt: "showtable"
},
mounted() {
document.head.title.innerHTML = this.title
}
})
</script>
第二种使用的场景比较多,但是局势的使用情况还是得根据具体的需求来选择。