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的報錯javascript

可是keep-alive標識不重複建立組件實例,也就是隻會觸發一次created mounted事件,html

利用二者能夠對組件的複用進行比較精細的管理vue

相關文章
相關標籤/搜索