VueJs 上有一个小型测试应用程序。问题的本质是当调用close函数的时候应该赋值this.selected_tab = 'collections',其实这并没有发生。莫名其妙。
Vue.component('collections', {
template: "#collections",
data: function () {
return {
collections: ['collection1', 'collection2', 'collection3']
}
}
})
var main = new Vue({
el: "#main",
data: {
selected_tab: 'collections',
tabs: ['collections'],
lists: [
'collection1',
'collection2',
'collection3'
]
},
methods: {
showTab: function (tab) {
this.selected_tab = tab;
},
selectList: function (selected) {
console.log(selected)
this.tabs.push(selected)
this.selected_tab = selected;
},
isActive: function (tab) {
var result = false;
if (this.selected_tab === tab) {
result = true;
}
return result;
},
close: function (index) {
this.selected_tab = 'collections';
this.tabs.splice(index, 1);
console.log(this)
}
}
});
body {
padding: 10px;
font: 14px "Lucida Grande", Helvetica, Arial, sans-serif;
}
a {
color: #00B7FF;
}
ul.nav {
margin-left: 0px;
padding-left: 0px;
list-style: none;
}
.nav li {
float: left;
}
ul.nav a {
display: block;
padding: 10px;
margin: 0 5px;
background-color: #d4d8f4;
border: 1px #333;
text-decoration: none;
color: #333;
text-align: center;
}
ul.nav a:hover {
background-color: #77de9a;
color: #8f34be;
}
ul.nav a:active {
background-color: #77de9a;
color: #8f34be;
}
ul.nav a.active {
background: #77de9a;
}
th.active {
color: #fff;
}
th.active .arrow {
opacity: 1;
}
<template id="collections">
<div class="collections">
<div v-for="collection in collections"><a @click.prevent="$emit('select', collection)" href="">{{ collection }}</a></div>
</div>
</template>
<div id="main" @keyup.v="test">
<div class="navbar navbar-inverse">
<ul class="nav nav-tabs">
<li v-for="key, index in tabs"><a href="" @click.prevent="showTab(key)" :class="{ active: isActive(key) }" :id="key">{{ key }}
<button @click.prevent="close(index)" v-if="key !== 'collections'">x</button></a></li>
</ul>
</div>
<collections v-if="selected_tab === 'collections'" v-on:select="selectList"></collections>
</div>
这是此应用程序的链接:https ://jsfiddle.net/pzbv3bny/
因为点击事件弹出,并且调用了两个处理程序:
<button>
-close(index)
<li>
-showTab(key)
为避免这种情况,您可以使用修饰符
.stop
: