在项目中常常需要切换不同的组件,这时候我们就可以使用vue内置的动态组件的方式来实现。
component 组件:在页面中通过使用component元素,在根据组件中的is属性来动态的切换不同的组件。
demo:
<template> //index.vue
<div class="contain-wrap">
<input type="button" @click="fatherBtn()" value="点击显示子组件">
<component :is="which_to_show" @fatherEvent="btnclick" ></component>
</div>
</template>
<script>
import FoodNews from "./foodNews"
import List from "./list"
import About from "./about"
export default {
name: "index",
components:{
List,
FoodNews,
},
data() {
return {
arr:['123','如图表'],
content:'',
which_to_show:"List",
params:"动态主键之间的传参"
};
},
methods:{
btnclick(params){
console.log(`呜呜~ 我被子组件${params}触发了 嘤嘤`)
},
fatherBtn(){
let arr=["List","FoodNews"]
let index=arr.indexOf(this.which_to_show)
if(index<2){
this.which_to_show=arr[index+1]
}else{
this.which_to_show = arr[0];
}
}
},
created() {},
};
</script>
<style module lang="scss">
.title{
color:purple;
}
</style>
子组件:
<template>//foodNews.vue
<div :class="$style.container">
<input type="button" @click="btnClick()" value="子组件操作这个值">
</div>
</template>
<script>
export default {
name: "FoodNews",
data() {
return {};
},
methods: {
btnClick(){
this.$emit("fatherEvent","foodNews")
}
}
};
</script>
<style module lang="scss">
.container{
width: 500px;
height:500px;
}
.title{
color:skyblue;
}
</style>
<template>//list.vue
<div class="contain-wrap" :style="{backgroundImage: 'url('+backgroundImg+')'}">
<div class="contain" >
<input type="button" @click="btnClick3()" value="List子组件操作这个值">
</div>
</div>
</template>
<script>
import NxNav from "../components/NxNav";
export default {
name: "index",
data() {
return {
backgroundImg:require('@/assets/foot/17.jpg'),
}
},
methods:{
btnClick3(){
this.$emit("fatherEvent","list")
}
},
mounted(){
},
}
</script>
<style scoped lang="scss">
.contain-wrap{
height: auto;
min-height:500px;
display: flex;
flex-direction: column;
}
</style>
点击点击显示子组件按钮就可以实现动态组件之间的切换。
动态组件传参:
通过上面的demo可以实现组件之间的切换,其实也是可以给动态组件传值的。
demo: 还是上面那个demo只不过在上面加上了一些传值的内容
//index.vue
<component :is="which_to_show" :tt="params" :ff="arr" :yy="which_to_show"></component>
props:{//list.vue
tt:{
type:String
},
ff:{
type:Array
},
yy:{
type:String
}},
created() {
console.log(this.tt)
console.log(this.yy)
console.log(this.ff)
},
props:{//foodNews.vue
tt:{
type:String
},
ff:{
type:Array
},
yy:{
type:String
}
},
created() {
console.log(this.tt)
console.log(this.yy)
console.log(this.ff)
},
效果图:
通过控制台打印你会发现,只要绑定到动态组件上的属性,在每一个组件中都可以获取到,并且也可以在动态组件中绑定事件
keep-alive:动态切换掉的组件是被移除掉了,如果把切换出去的组件保留在内存中,可以保留它的状态或避免重新渲染。为此可以添加一个 keep-alive 指令参数:
<keep-alive>
<component @fatherEvent="btnclick" :is="which_to_show" :tt="params" :ff="arr" :yy="which_to_show"></component>
</keep-alive>
通过使用keep-alive来存储被移除的组件的状态。这样用户再切换回来的时候仍然可以看到之前的内容。
actived、deactivated钩子函数的使用
keep-alive可以配合actived、deactivated钩子函数使用,actived表示在keep-alive缓存组件被激活时调用。deactivated表示在 keep-alive 缓存的组件被停用时调用。因此我们可以在这个钩子函数中做一些逻辑数据处理