[英]Reflect changes of same Vue Component to different routes
I have a Filter tab component.我有一个过滤器选项卡组件。 That i used in different routes.我在不同的路线上使用过。 Whenever click on any tab it is being active.每当单击任何选项卡时,它都处于活动状态。 After clicking one i want to make the same tab to be active in other routes also.单击一个后,我想让相同的选项卡在其他路线中也处于活动状态。 How can i do so?我该怎么做? Any article or suggestion will be really helpful.任何文章或建议都会非常有帮助。
Here's my filter tab component这是我的过滤器选项卡组件
<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>
I would highly recommend Vuex as per previous comments.根据之前的评论,我强烈推荐 Vuex。 But since you are asking for other solutions.但是,既然您要寻求其他解决方案。 Here are some not so elegant approaches:以下是一些不太优雅的方法:
Global Event Bus - keep the active tab in a global EventBus state that will also listen to changes, and emit changes.全局事件总线 - 将活动选项卡保留在全局 EventBus state 中,该选项卡还将监听更改并发出更改。 As this will not be destroyed between routes, you can get the event bus state on route change (component mount/create).由于这不会在路由之间被破坏,您可以在路由更改(组件安装/创建)时获取事件总线 state。
Use Portal-Vue to teleport filter tab component on demand to other views/routes keeping it's state.使用 Portal-Vue 将过滤器选项卡组件按需传送到其他视图/路线,使其保持 state。 More: https://github.com/LinusBorg/portal-vue更多: https://github.com/LinusBorg/portal-vue
Keep active tab in url hash https://example.com/#tab-1
or URLSearchParam https://example.com/route1?tab=2
. Keep active tab in url hash https://example.com/#tab-1
or https://example.com/route1?tab=2
. And load param/hash on route change/component mount.并在路由更改/组件安装时加载参数/哈希。 The biggest downside to that is that you need to manually pass the hash or URL search param to every link.最大的缺点是您需要手动将 hash 或 URL 搜索参数传递给每个链接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.