【发布时间】:2021-02-14 09:17:52
【问题描述】:
我有一个过滤器选项卡组件。我在不同的路线上使用过。每当单击任何选项卡时,它都处于活动状态。单击一个后,我想让相同的选项卡在其他路线中也处于活动状态。我该怎么做?任何文章或建议都会很有帮助。
这是我的过滤标签组件
<template>
<div class="filter-container">
<div
v-for="(item, index) in items"
:key="index"
v-ripple
:identifier="random()"
:class="[`item i${item.id}`, { 'active': activeId == item.id }]"
@click="scrollInto(item.id, $event)"
>
{{ item.label }}
</div>
</div>
</template>
<script>
export default {
name: 'FilterTabs',
props: {
items: {
type: Array,
required: true,
},
},
data() {
return {
activeId: this.items.length ? this.items[0].id : null,
};
},
watch: {
items(newValue, oldValue) {
this.activeId = newValue[0].id;
},
},
methods: {
scrollInto(id, event) {
this.activeId = id;
setTimeout(() => {
const identifier = event.target.attributes.identifier.value;
document.querySelectorAll(`[identifier='${identifier}']`)[0].scrollIntoView({
behavior: 'smooth', block: 'center', inline: 'center',
});
// var selectors = document.querySelectorAll(`.i${id}`);
// selectors.forEach((node) => {
// node.scrollIntoView({
// behavior: 'smooth', block: 'center', inline: 'center',
// });
// })
}, 100);
this.$emit('onTagChange', id);
},
random() {
return Math.random().toString(36).substr(2, 9) + '-' + Math.random().toString(36).substr(2, 9);
},
},
};
</script>
【问题讨论】:
-
route2是另一个组件吗?似乎是学习 Vuex 的好时机;) -
你可以尝试使用
props的概念或者可以学习Vuex如果两个组件的路由在不同的组件中,但是如果它们在同一个组件中那么你可以使用data维护页面的本地状态。 -
还有什么不用vuex的概念吗?喜欢一个实例,但不同位置的多个视图?
标签: javascript vue.js vuejs2 vue-component vue-router