用key管理可复用元素

先看看不用key管理可复用元素的代码。Vue 会尽可能高效地渲染元素,通常会复用已有元素而不是从头开始渲染。这么做,除了使 Vue 变得非常快之外,还有一些有用的好处,那就是在切换input时不会清楚里面的数据。
<!
DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <script type="text/javascript" src="vue.js"></script> </head> <body> <div id="app"> <span v-if="loginType === 'username'"> <label>Username</label> <input placeholder="Enter your username" > </span> <span v-else> <label>Email</label> <input placeholder="Enter your email address" > </span> <button v-on:click="test">切换</button> </div> </body> <script> var vm = new Vue({ el:"#app", data:{ loginType: 'username' }, methods:{ test:function(){ if(this.loginType != 'username'){ return this.loginType = 'username' } return this.loginType = 'email' } } }) </script> </html>

我么再看看使用key管理可复用元素。添加key属性,则这两个元素是相互独立,不再复用。这样当我们在切换input时里面的数据会被清除。

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script type="text/javascript"  src="vue.js"></script>
</head>
<body>
<div id="app">
    <span v-if="loginType === 'username'">
        <label>Username</label>
        <input placeholder="Enter your username" key="username-input">
    </span>
    <span v-else>
        <label>Email</label>
        <input placeholder="Enter your email address" key="email-input">
    </span>
    <button v-on:click="test">切换</button>
</div>
</body>
    <script>
    var vm = new Vue({
        el:"#app",
        data:{
            loginType: 'username'
         },
        methods:{
            test:function(){
                if(this.loginType != 'username'){
                    return this.loginType = 'username'
                }
                return this.loginType = 'email'
            }
        }
    })
</script>
</html>

 

posted @ 2017-10-21 11:46  黄鹂  阅读(845)  评论(0编辑  收藏  举报