Vue中keep-alive保持状态

1.在router-view外嵌套keep-alive标签;

2.在组件中设置一个属性保存路由;

3.在组件actived函数中将路由push到this.$router中;

4.在beforeRouterLeave中将概述性更新。

demo:

<keep-alive exclude="Profile">
      <router-view></router-view>
</keep-alive>




<template>
    <div>
        <h2>我是首页内容哈哈哈</h2>
        <p>首页呵呵</p>
        <router-link to="/home/news">新闻</router-link>
        <router-link to="/home/message">消息</router-link>
        <router-view></router-view>
    </div>
</template>

<script>
    export default {
        name:'Home',
        data(){
            return {
                // home页面默认路由值
                path:'/home/news'
            }
        },
        created() {
            console.log('home created');
        },
        destroyed() {
            console.log('home destroyed');
        },
        activated() {
            this.$router.push(this.path);
        },
        // 这个函数执行太晚,执行时路由已经变调了,所以保存不下来
        // deactivated() {
        //     this.$router.push(this.path);
        // },
        beforeRouteLeave (to, from, next) {
            // 离开页面之前记住页面路由
            console.log(this.$route.path);
            this.path = this.$route.path;
            next();
        }
    }
</script>

<style scoped>
</style>

keep-alive包含的组件只会创建一次,要想某个组件每次都去创建 ,可在keep-alive中加入exclude属性,加入组件名。

发布了43 篇原创文章 · 获赞 19 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/qianlixiaomage/article/details/104232111
今日推荐