鍍金池/ 問答/HTML/ v-bind:key 綁定的作用是什么?

v-bind:key 綁定的作用是什么?

https://cn.vuejs.org/v2/guide...
這里的示例改成如下:

    <style>
    #demo,
    .demo,
    .content .demo {
        border: 1px solid rgb(238, 238, 238);
        border-radius: 2px;
        padding: 25px 35px;
        margin-top: 1em;
        margin-bottom: 40px;
        font-size: 1.2em;
        line-height: 1.5em;
        -webkit-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
        user-select: none;
        overflow-x: auto;
    }

    #demo> :first-child,
    .demo> :first-child,
    .content .demo> :first-child {
        margin-top: 0;
    }

    .dynamic-component-demo-tab-button {
        padding: 6px 10px;
        border-top-left-radius: 3px;
        border-top-right-radius: 3px;
        border: 1px solid rgb(204, 204, 204);
        cursor: pointer;
        background: rgb(240, 240, 240);
        margin-bottom: -1px;
        margin-right: -1px;
    }

    .dynamic-component-demo-tab-button-active {
        background: rgb(224, 224, 224);
    }
    </style>
</head>

<body>
 
    <!-- 動態(tài)組件  -->
    <div id="dynamic-component-demo" class="demo">
        <button v-for="tab,index in tabs"
        class="dynamic-component-demo-tab-button"
        :class="{'dynamic-component-demo-tab-button-active': tab === currentTab }"
        @click="currentTab = tab">   
      {{ tab }}
        </button>
        <component :is="currentTabComponent" class="dynamic-component-demo-tab">
        </component>
    </div>
    <script type="text/javascript">
    var tabHome = {
        template: ` <p>Home component  </p> `
    }
    var tabPosts = {
        template: ` <p>Posts component  </p> `
    }
    var tabArchive = {
        template: ` <p>Archive component  </p> `
    }
    var app = new Vue({
        el: "#dynamic-component-demo",
        data: {
            tabs: ['Home', 'Posts', 'Archive'],
            currentTab: 'Home',
        },
        components: {
            "tab-home": tabHome,
            "tab-posts": tabPosts,
            "tab-archive": tabArchive,
        },
        computed: {
            currentTabComponent: function() {
                return 'tab-' + this.currentTab.toLowerCase()
            }
        }
    });
    </script>

與原文內(nèi)容不一致的地方是去掉了按鈕上面的

v-bind:key="tab"

通過hhttps://cn.vuejs.org/v2/guide... 了解到v-for做列表渲染的時(shí)候可以有三個(gè)參數(shù)(value,key,index)分別代表對象屬性的值,對象的屬性名和鍵值對的索引。官網(wǎng)動態(tài)組件這里的 tabs: ['Home', 'Posts', 'Archive'], 也只是普通的字符串?dāng)?shù)組。
所以,動態(tài)數(shù)組那里 v-bind:key="tab" 有這個(gè)設(shè)定有什么作用。

回答
編輯回答
厭遇

參考這段文檔:列表渲染 key。Vue 為了節(jié)省資源重復(fù)利用已有 DOM 節(jié)點(diǎn),要求開發(fā)者給列表中的元素加上唯一的 key,這樣在排序之類的操作時(shí),就不需要銷毀創(chuàng)建新節(jié)點(diǎn)了。

2017年3月20日 15:37
編輯回答
陪她鬧

增刪或切換順序時(shí)提高性能,console warnning里面有提示

2017年3月13日 19:08