1 Overview
Vue will render elements as efficiently as possible, often reusing existing elements rather than rendering them from scratch.
key solves a situation outside the above problem: these two elements are completely independent, do not reuse them.
2. Example
<!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>
Each time you toggle, the input box will be re-rendered.