vue中使用key管理可復用的元素


1、概述

Vue 會盡可能高效地渲染元素,通常會復用已有元素而不是從頭開始渲染。

key解決上述問題之外的情景:這兩個元素是完全獨立的,不要復用它們。

2、示例

<!DOCTYPE html>
<html lang="zh">

    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>vue中使用key管理可復用的元素</title>
    </head>

    <body>
        <div id="root">
            <template v-if="loginType === 'username'">
                <label>Username</label>
                <input placeholder="Enter your username" key="username-input">
            </template>
            <template v-else>
                <label>Email</label>
                <input placeholder="Enter your email address" key="email-input">
            </template>
            <button @click="toggleLoginType">Toggle login type</button>
        </div>
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

        <script type="text/javascript">
            var vm = new Vue({
                el: '#root',
                data: {
                    loginType: 'username'
                },
                methods: {
                    toggleLoginType: function() {
                        return this.loginType = this.loginType === 'username' ? 'email' : 'username'
                    }
                }
            });
        </script>
    </body>

</html>

每次切換時,輸入框都將被重新渲染。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM