keep-alive是vue內置的一個組件,可以使被它包含的組件處於保留狀態,或避免被重新渲染。
在keep-alive標籤內部添加
include:字符串或正則表達式。只有匹配的組件會被緩存
exclude: 字符串或正則表達式。任何匹配的組件都不會被緩存。
hello組件:
<style scoped lang="less">
@import "./a.css";
</style>
<template>
<div class="hello">
hello組件
<div @click="TabCom">TabCom</div>
<com1 v-if="show"></com1>
<cpm2 v-else></cpm2>
<keep-alive include="aaa">
<com1 v-if="show"></com1>
<cpm2 v-else></cpm2>
</keep-alive>
</div>
</template>
<script>
import aaa from "./a.css";
import com1 from "./com1.vue";
import cpm2 from "./cpm2.vue";
export default {
name: "HelloWorld",
components: {
com1,
cpm2
},
data() {
return {
show: true,
msg: "Welcome to Your Vue.js App",
items: "Welcome to Your Vue.js App"
};
},
mounted() {},
methods: {
TabCom() {
this.show = !this.show;
}
}
};
</script>
com1組件:
<template>
<div class="hello">
<button @click="BtnClick">Btn</button>
<input type="text">
<div>{{message}}</div>
</div>
</template>
<script>
export default {
name: "Com1",
data() {
return {
message:'messageCom1'
};
},
mounted() {
},
methods: {
BtnClick(){
this.message=="messageCom1-1"? this.message="messageCom1": this.message="messageCom1-1"
}
}
};
</script>
<style scoped>
</style>
com2組件:
<template>
<div class="hello">
<button @click="BtnClick">Btn2</button>
<input type="text">
<div>{{message}}</div>
</div>
</template>
<script>
export default {
name: "aaa",
data() {
return {
message:'messageCom2'
};
},
mounted() {
},
methods: {
BtnClick(){
this.message=="messageCom2-2"? this.message="messageCom2": this.message="messageCom2-2"
}
}
};
</script>
<style scoped>
</style>
結合router緩存部分頁面:
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import HelloWorld1 from '@/components/HelloWorld1'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld,
meta:{
keepAlive:true//需要被緩存
}
},
{
path: '/index',
name: 'HelloWorld1',
component: HelloWorld1,
meta:{
keepAlive:false//不需要被緩存
}
},
]
})
<template>
<div id="app">
<img src="./assets/logo.png" />
<button @click="tabC">tabC切換路由</button>
<keep-alive>
<router-view v-if="$route.meta.keepAlive" />
</keep-alive>
<router-view v-if="!$route.meta.keepAlive"/>
</div>
</template>
<script>
export default {
name: "App",
data(){
return{
msg:'HelloWorld'
}
},
methods:{
tabC(){
this.$router.push({
name:this.msg=="HelloWorld"?this.msg="HelloWorld1":this.msg='HelloWorld'
})
}
}
};
</script>
<style>
#app {
font-family: "Avenir", Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>