component -- is 切換組件
1.有的時候,在不同組件之間進行動態切換,有兩種方法一種使用v-if 或者v-show
來控制組件之間的顯示切換
2.另外一種配合component標籤和v-bind 搭配is使用例如:
<component v-bind:is="切換組件的名"></component>
3.簡單的說:
<component> 元素,動態地綁定多個組件到它的 is 屬性
<keep-alive> 保留狀態,避免重新渲染
官方案例地址
案例 -選擇不同radio展示不同組件
1.component 每次只能顯示一個組件,組件之間切換的時候就是銷燬之前的組件
,重建新的組件這樣會浪費性能
2.想查看上面話中具體的代碼效果,可以在組件中加入聲明週期鉤子,斷點來看
3.詳解解決這類問題使用<keep-alive></keep-alive> 來解決例如下面案例可以寫成:
<keep-alive>
<component :is="tab"></component>
</keep-alive>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
</head>
<body>
<div id="app">
<input type="radio" v-model="tab" value="myCom1">組件一號
<input type="radio" v-model="tab" value="myCom2">組件二號
<!--等號左邊是子組件,右邊是父組件,因此tab是父組件的data,通過改變來切換組件-->
<component :is="tab"></component>
</div>
<template id="com1">
<p> {{title}}</p>
</template>
<template id="com2">
<p> {{title}}</p>
</template>
<script>
let myCom1 = {
template:'#com1',
data(){
return {
title:'子組件一號',
}
},
};
let myCom2 = {
template:'#com2',
data(){
return {
title:'子組件二號',
}
},
};
var vm = new Vue({
el: '#app',
data:{
tab:"myCom1"
},
components:{
myCom1,
myCom2,
}
});
</script>
</body>
</html>
案例二
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Examples</title>
<meta name="description" content="">
<meta name="keywords" content="">
<link href="" rel="stylesheet">
<script src="lib/vue.js"></script>
<style>
* {
margin: 0px;
padding: 0px;
}
html, body {
width: 100%;
height: 100%;
}
footer ul {
display: flex;
position: fixed;
bottom: 0;
left: 0;
width: 100%;
height: 40px;
}
ul li {
flex: 1;
text-align: center;
list-style: none;
height: 40px;
line-height: 40px;
background: gray;
}
</style>
</head>
<body>
<div id="app">
<keep-alive>
<component :is="who"></component>
</keep-alive>
<footer>
<ul>
<li><a @click="who='first'">首頁</a></li>
<li><a @click="who='second'">中間頁</a></li>
<li><a @click="who='third'">尾頁</a></li>
</ul>
</footer>
</div>
<template id="first">
<div>
首頁<input>
</div>
</template>
<template id="second">
<div>
中間頁
</div>
</template>
<template id="third">
<div>
尾頁
</div>
</template>
<script type="text/javascript">
var first = {
template: "#first",
methods: {}
}
var second = {
template: "#second",
methods: {}
}
var third = {
template: "#third",
methods: {}
}
var vm = new Vue({
el: "#app",
data: {
who: 'first'
},
components: {
first,
second,
third,
}
})
</script>
</body>
</html>