vue学习笔记一:用Key管理可复用元素

vue为了高效的渲染元素,会尽可能的复用组件,而不是从头渲染,如下案例

<template>
        <div id="app">
            <template v-if="loginType === 'username'">
                <label for="username">username</label>
                <input type="text" placeholder="please enter username"/>
            </template>
            <template v-else>
                <label for="email">email</label>
                <input type="text" placeholder="please enter email"/>
            </template>
            <button @click="toggleType">toggle loginType</button>
        </div>
    </template>
    <script>
        export default {
            name: 'app',
            data() {
                return {
                    loginType : "username"
                }
            },
            methods: {
                toggleType : function(){
                    this.loginType = this.loginType == "username" ? "email" : "username";
                }
            }
        }
    </script>

在输入框中输入值后,点切换,你会发现输入的值还在,加个key就能让vue重新渲染input元素

<template>
    <div id="app">
        <template v-if="loginType === 'username'">
            <label for="username">username</label>
            <input type="text" placeholder="please enter username" key="loginUsername"/>
        </template>
        <template v-else>
            <label for="email">email</label>
            <input type="text" placeholder="please enter email" key="loginemail"/>
        </template>
        <button @click="toggleType">toggle loginType</button>
    </div>
</template>

 

posted @ 2017-08-15 15:46  点点乐淘淘  阅读(592)  评论(0编辑  收藏  举报