Vue keep-alive缓存路由信息

在不使用keep-alive时,通过路由跳转到另一组件上时,上一个组件会被vue销毁,在次进入,页面会保持初始状态,不会对用户的更改保留,如果需要包作在某组件上的更改,就可以使用keep-alive保存路由入口

		<keep-alive>
           <router-view></router-view>
        </keep-alive>
<body>
<div id="app"></div>
<script>
    let One = {
        template: `<div>
            <h1 @click="changeColor">One</h1>
    </div>`,
        methods: {
            changeColor(e) {
                e.target.style.color = 'green';
            }
        },
        created() {
            console.log("One-created");
        },
        mounted() {
            console.log("One-mounted");
        },
        destroyed() {
            console.log('One-destroyed');
            //使用了keep-alive 组件不再销毁,所以这条不会打印,不用keep-alive会显示这条调试,也就是说使用keep-alive组件缓存了不会销毁,这种实现视需求而定,是否要再返回某一页面时在页面上做出的更改保留
        }
    };
    let Two = {
        template: `<div>
            <h1>Two</h1>
    </div>`,
        created() {
            console.log("Two-created");
        },
        mounted() {
            console.log("Two-mounted");
        },
        destroyed() {
            console.log('Two-destroyed');
        }
    };
    let App = {
        template: `<div id="app">
           <router-link :to="{name:'One'}">One</router-link>
           <router-link :to="{name:'Two'}">Two</router-link>

           <keep-alive>
           <router-view></router-view>
           </keep-alive>

        </div>`
    };

    Vue.use(VueRouter);
    let router = new VueRouter({
        routes: [
            {
                name: 'One',
                path: '/one',
                component: One
            },
            {
                name: 'Two',
                path: '/two',
                component: Two
            }
        ]
    });

    let vm = new Vue({
        el: "#app",
        components: {
            App
        },
        template: `<App></App>`,
        router
    })
</script>
</body>
发布了68 篇原创文章 · 获赞 89 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/printf_hello/article/details/104523477