網(wǎng)站建設主題與建設目標最火網(wǎng)站排名
一,場景
A頁面是表單頁面,填寫后需要跳轉(zhuǎn)B頁面。如果B頁面不操作返回的話,應該能還原A頁面的內(nèi)容,而如果B頁面點擊提交,再回到A頁面的時候,應該清除緩存。
二,實現(xiàn)方法
A頁面要緩存數(shù)據(jù),則需要用keep-alive包裹。
B頁面點擊提交后需要清空緩存,則需要清除A頁面的keep-alive緩存。
于是可以利用keep-alive的:include屬性,只有在這個列表中的頁面才具備緩存,不在這個列表中的頁面不具備緩存,下次進入時重新渲染。
被 keep-alive 包裹的組件的生命周期是有區(qū)別于普通的組件。
被 keep-alive 包裹的組件中,會多出兩個生命周期 activated、deactivated。
第一次進入被 keep-alive 包裹的組件中的時候會依次調(diào)用 beforeCreate -> created -> beforeMount -> mounted -> activated,其后的進入皆只會調(diào)用 activated,因為組件被緩存了,再次進入的時候,就不會走 創(chuàng)建、掛載 的流程了。
被 keep-alive 包裹的組件退出的時候就不會再執(zhí)行 beforeDestroy、destroyed 了,因為組件不會真正意義上被銷毀,相對應的組件退出的時候會執(zhí)行 deactivated 作為替代。
于是可以想到:
第一步:路由發(fā)生改變時(例如跳轉(zhuǎn)A頁面時),將A頁面加入keep-alive緩存include,然后頁面開始渲染
第二步:A頁面填寫表單完成后跳轉(zhuǎn)B頁面
第三步:B頁面提交表單完成后把A頁面從include中移除。
第四步:這時候無論從哪里進入A頁面,都需要重新加入include緩存,并重新渲染了(重新走第一步)。而如果沒有第三步的移除緩存,則再進入A時會拿緩存的A頁面。
三,具體的實現(xiàn)代碼邏輯
因為我是拿vue-template-admin做演示的,就講這里面是如何實現(xiàn)的。
第一步:keep-alive包裹組件
主布局頁面:
<template><section class="app-main"><transition name="fade-transform" mode="out-in"><keep-alive :include="cachedViews"><router-view :key="key" /></keep-alive></transition></section>
</template>
<script>
export default {name: "AppMain",computed: {cachedViews() {return this.$store.state.tagsView.cachedViews},key() {return this.$route.path}}
}
</script>
第二步:看vuex中的tagsView模塊:
const state = {cachedViews: []
}const mutations = {ADD_CACHED_VIEW: (state, view) => {if (state.cachedViews.includes(view.name)) returnif (!view.meta.noCache) {state.cachedViews.push(view.name)}},DEL_CACHED_VIEW: (state, view) => {const index = state.cachedViews.indexOf(view.name)index > -1 && state.cachedViews.splice(index, 1)},
}
export default {namespaced: true,state,mutations,actions
}
這里就是添加include和移除的方法。
第三步:看router.js文件中的配置
{path: "/test",component: Layout,redirect: "/test/test-one",children: [{path: "test-one",component: () => import("@/views/test-one/index"),name: "TestOne",meta: { title: "表單測試", icon: "el-icon-warning", noCache: false }},{path: "test-two",hidden: true,component: () => import("@/views/test-two/index.vue"),name: "TestTwo",meta: {title: "表單提交",activeMenu: "/test/test-one",noCache: true}}]}
主要就是name屬性和meta中的noCache屬性。
第四步:看keep-alive的include緩存是啥時候加上的
看下圖,可以知道,是監(jiān)聽了當前路由的變化。當路由發(fā)生變化時,就調(diào)用vuex中的ADD_CACHED_VIEW方法,把當前頁面對應的name加入數(shù)組中。因為路由變化時,頁面還沒有渲染,所以這時候加入,頁面渲染時是能夠緩存起來的。
第五步:看提交表單頁移除緩存
當A頁面已經(jīng)被緩存,填寫表單后進入B頁面,這時提交表單,則需要移除A的緩存。于是B頁面:
<template><div class="activity-list">第二個測試頁面<button @click="back">提交代碼</button></div>
</template><script>
export default {name: "TestTwo",data() {return {}},created() {},mounted() {},methods: {back() {this.$store.commit("tagsView/DEL_CACHED_VIEW", { name: "TestOne" })this.$router.go(-1)}}
}
</script><style scoped lang="scss"></style>
可以注意到,它是調(diào)用tagsView/DEL_CACHED_VIEW移除的。因為先移除了,所以這時候返回A頁面,會重新將A頁面加入緩存,且重新開始渲染。