Vue keep-alive Cache routing information

When not in use keep-alive, by routing jump to another component, the component will be destroyed vue, enter at times, the page will maintain the initial state, the user does not change the reservation, if you need to make in package changes on a component, can be used to save the routing keep-alive inlet

		<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>
Published 68 original articles · won praise 89 · views 10000 +

Guess you like

Origin blog.csdn.net/printf_hello/article/details/104523477