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>
<!-- 动态组件 -->
<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>
与原文内容不一致的地方是去掉了按钮上面的
v-bind:key="tab"
通过hhttps://cn.vuejs.org/v2/guide... 了解到v-for做列表渲染的时候可以有三个参数(value,key,index)分别代表对象属性的值,对象的属性名和键值对的索引。官网动态组件这里的 tabs: ['Home', 'Posts', 'Archive'], 也只是普通的字符串数组。
所以,动态数组那里 v-bind:key="tab" 有这个设定有什么作用。
增删或切换顺序时提高性能,console warnning里面有提示