Vue中 key keep-alive

keep-alive key

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script type="text/javascript" src="./vue.js"></script>
</head>
<body>
    <div id="app">
        <keep-alive>
            <child-component key="1" v-if="seen" name="1"></child-component>
            <child-component key="2" v-if="!seen" name="2"></child-component>
        </keep-alive>
        <button @click="toggle">toggle</button>
    </div>
    <script type="text/javascript">
        Vue.component('child-component', {
            template: `<input type="text" placeholder="enter">`,
            data() {
                return {}
            },
            props: ["name"],
            mounted() {
                console.log(`${this.name} mounted`)
            }
        })
        const vm = new Vue({
            el: "#app",
            data: {
                seen: true
            },
            methods: {
                toggle() {
                    this.seen = !this.seen;
                }
            }
        })
    </script>
</body>
</html>

key是标识元素不再被复用,注意key是Vue中的一个保留的属性,不能作为prop传递给子组件,否则会在控制台看到Vue的报错

但是keep-alive标识不重复创建组件实例,也就是只会触发一次created mounted事件,

利用两者可以对组件的复用进行比较精细的管理

    原文作者:zhangguixu
    原文地址: https://segmentfault.com/a/1190000016432362
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞