我的应用程序的导航栏有1个父组件和2种子组件。
父Vue组件具有以下代码:
<template>
<div class="be-submenu__inner">
<ul class="be-submenu__categories">
<category-tab name="Events" @setActive="toggleActive"></category-tab>
<category-tab name="Articles" @setActive="toggleActive"></category-tab>
</ul>
<news-cards></news-cards>
</div>
</template>
<script>
import NewsCards from './NewsCards.vue'
import CategoryTab from './CategoryTab.vue'
export default {
name: 'be-nav-submenu-news',
data() {
return{
queryCategory: null,
posts: ''
}
},
methods:
toggleActive: function (selectedTab) {
console.log(selectedTab)
}
},
components: {
CategoryTab,
NewsCards
}
}
</script>
category-tab
个组件:
<template>
<li class="be-submenu__category">
<a :class="[titleStyle, { 'is-active': isActive }]" @mouseover="setActive">
{{ this.name }}
</a>
</li>
</template>
<script>
export default {
name: 'be-category-tab',
data() {
return {
titleStyle: 'be-submenu__category-link'
}
},
props: {
name: {
required: true
},
isActive: {
required: false,
default: false
}
},
methods: {
setActive: function () {
this.$emit('setActive', this.name)
}
}
}
</script>
我想要做的是在将光标放在其中一个上面后更新标签状态。假设我将鼠标悬停在第二个标签页上,其属性isActive
设置为true
。其他组件变为非活动状态,<news-cards>
组件的内容也会根据我选择的选项卡进行更新。
我假设我必须以某种方式跟踪'be-category-tab'
名称的所有子元素,并在触发自定义事件后更新其状态。 Vue文档让我对自定义事件感到困惑,所以现在我甚至不确定我是否正确使用它。
你能告诉我这可能是我的下一步吗?或许我应该使用其他东西,但自定义事件。提前谢谢。
答案 0 :(得分:0)
尝试:
Vue.component('category-tab', {
template: '<li class="be-submenu__category">' +
'<a :class="[titleStyle, { \'is-active \': isActive }]" @mouseover="setActive">' +
'{{ this.name }} {{ this.isActive }}' +
'</a></li>',
data() {
return {
titleStyle: 'be-submenu__category-link'
}
},
props: {
name: {
required: true
},
isActive: {
default: false
}
},
methods: {
setActive: function() {
this.$emit('setactive')
}
}
});
Vue.component('news-cards', {
template: '<div>New Cards : {{ proptest }}</div>',
props: { proptest: { default: ''} }
});
new Vue({
el: "#app",
data() {
return {
categoriesTab: [{
name: 'Events',
isActive: false
}, {
name: 'Articles',
isActive: false
}, {
name: 'Other category...',
isActive: false
}],
queryCategory: null,
posts: '',
name: ''
}
},
methods: {
deactiveAllCategories: function() {
for (var i = 0, length = this.categoriesTab.length; i < length; i++) {
this.categoriesTab[i].isActive = false;
}
},
setActive: function(category) {
this.deactiveAllCategories();
this.name = category.name;
category.isActive = true;
}
},
});
.be-submenu__category{
cursor: pointer;
}
.is-active {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.5/vue.js"></script>
<div id="app">
<div class="be-submenu__inner">
<ul class="be-submenu__categories">
<category-tab v-for="(category, index) in categoriesTab" @setactive="setActive(category)" :name="category.name" :is-active="category.isActive" :key="category">
</category-tab>
</ul>
<news-cards :proptest="name"></news-cards>
</div>
</div>