非缓存组件:在来回切换组件后,组件状态会丢失,即会重新渲染组件。示例如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!--Vue安装-->
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
</head>
<body>
<div id="app">
<button @click="currentComp='component1'">组件一</button>
<button @click="currentComp='component2'">组件二</button>
<br>
<br>
<component :is="currentComp"></component>
</div>
</body>
<script>
<!--定义组件对象-->
let component1 = {
data: function () {
return {
count: 1,
}
},
template: '<button style="background-color: #13E8E9" @click="count++">累加{{count}}</button>',
};
let component2 = {
data: function () {
return {
count: 1,
}
},
template: '<button style="background-color: red" @click="count++">累加{{count}}</button>',
};
new Vue({
el: '#app',
data: {
currentComp: component1,
},
methods: {},
//局部注册组件
components: {
'component1': component1,
'component2': component2,
}
})
</script>
</html>
缓存组件:来回切换不会丢失状态
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!--Vue安装-->
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
</head>
<body>
<div id="app">
<button @click="currentComp=component1">组件一</button>
<button @click="currentComp=component2">组件二</button>
<br>
<br>
<keep-alive>
<component :is="currentComp"></component>
</keep-alive>
</div>
</body>
<script>
<!--定义组件对象-->
let component1 = {
data: function () {
return {
count: 1,
}
},
template: '<button style="background-color: #13E8E9" @click="count++">累加{{count}}</button>',
};
let component2 = {
data: function () {
return {
count: 1,
}
},
template: '<button style="background-color: red" @click="count++">累加{{count}}</button>',
};
new Vue({
el: '#app',
data: {
//注意component1和'component1'渲染出来的是不同的实例。
currentComp: component1,
},
methods: {},
//局部注册组件
components: {
component1,
component2,
}
})
</script>
</html>