【问题标题】:Reflect changes of same Vue Component to different routes将同一个 Vue 组件的变化反映到不同的路由上
【发布时间】: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


【解决方案1】:

根据之前的 cmets,我强烈推荐 Vuex。但是,既然您要寻求其他解决方案。以下是一些不太优雅的方法:

  1. 全局事件总线 - 将活动选项卡保持在全局 EventBus 状态,该状态还将侦听更改并发出更改。由于这不会在路由之间被破坏,您可以在路由更改(组件安装/创建)时获取事件总线状态。

  2. 使用 Portal-Vue 将过滤器选项卡组件按需传送到其他视图/路由,保持其状态。更多:https://github.com/LinusBorg/portal-vue

  3. 在 URL 哈希 https://example.com/#tab-1 或 URLSearchParam https://example.com/route1?tab=2 中保持活动标签。并在路由更改/组件安装时加载参数/哈希。最大的缺点是您需要手动将哈希或 URL 搜索参数传递给每个链接。

【讨论】:

  • 使用 Vuex 解决。但是门户视图似乎正是我需要的组件......谢谢。
猜你喜欢
  • 2019-12-10
  • 1970-01-01
  • 2020-01-07
  • 1970-01-01
  • 2020-07-24
  • 1970-01-01
  • 2018-07-11
  • 2018-11-17
  • 1970-01-01
相关资源
最近更新 更多