Adjust alterations in a Vue Component to apply to separate routes

I have a Filter tab component that I use in various routes. When I click on a tab, it becomes active. After clicking on one tab, I want it to remain active in other routes as well. How can I achieve this? Any suggestions or articles would be greatly appreciated.

https://i.sstatic.net/JI1II.png

Below is my code for the 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>

Answer №1

If you're looking for alternative solutions to Vuex, here are a few options:

  1. Utilize a Global Event Bus to manage the active tab state. This EventBus can listen to changes and emit them as needed. Since it persists between routes, you can access the event bus state on route changes.

  2. Consider using Portal-Vue to teleport the filter tab component to other views/routes while preserving its state. More information can be found at: https://github.com/LinusBorg/portal-vue

  3. Store the active tab in the URL hash (e.g., https://example.com/#tab-1) or URL search parameter (e.g., https://example.com/route1?tab=2). Retrieve and load the hash or parameters on route changes/component mounts. One drawback is that you'll need to manually pass the hash or parameters to each link.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to update a page and retrieve fresh data from a service in Angular?

On my webpage, there is a table and two charts coming from three different controllers. I am looking for a way to refresh all of them simultaneously by clicking on a single refresh button. This will allow the data to be fetched from the webservice again an ...

JS/Electron Insert items individually

Apologies if my explanation is unclear. I have a function (shown below) that parses a JSON file and creates a grid of 1550 items. How can I add them one by one instead of all at once? Loading all 1500 items together is taking too long. function addItem () ...

Prevent event listeners from being triggered during the '$destroy' event. Error: $on function is undefined

As I attempt to halt all event listeners when the scope is destroyed, a certain error arises. The following error is displayed: TypeError: vm.$on is not a function; Even using vm.on(..) does not resolve the issue angular.module('app.layout&apo ...

Exploring jQuery functionalities for dynamic selector input

I have encountered a scenario where I must use dynamic ID's in the format of functionalDescription_IDNUMBER across my page. It is necessary to target specific areas based on the unique IDNUMBER associated with the clicked object. However, I am looking ...

Do you think it's feasible to configure cookies for express-session to never expire?

Is there a way to make cookies never expire for express-session? If not, what is the maximum maxAge allowed? I came across some outdated information on setting cookie expiration on SO (over 10 years old) and here on express, which mentions a maxAge of 1 y ...

VueJS together with Firebase: The guide to password validation

I am currently working on a web form developed using VueJS that enables authenticated users to modify their passwords. The backend system relies on Firebase, and I am facing a challenge in validating the user's current password before initiating the p ...

Looking to showcase a custom favicon on your Nuxt.js website hosted on Google App Engine?

Premise / Goal Currently, I am deploying a Nuxt.js app in SSR mode on Google App Engine. The issue I am facing is that the favicon is not being displayed on the site. Therefore, my aim is to troubleshoot and fix this problem. Steps taken: yarn build + gcl ...

Exposing the location data in vue-test-utils tests

My goal is to start each test with a fresh setup, such as creating a new localVue instance for each test. However, I have noticed that the state seems to be leaking between unit tests despite using vue-test-utils and jest with vue-router. To workaround t ...

Unable to create follow/unfollow feature with jquery ajax

Issue: While the database part for following and unfollowing actions is functioning correctly, there seems to be a problem with the jQuery and Ajax section. The follow button changes to unfollow (with some CSS styling) only after refreshing the page, rathe ...

Utilizing Node.js for Lambda Functions

I am attempting to retrieve a list of all EC2 instances in a specific region using a lambda function. Below is the code snippet I am using: const AWS = require('aws-sdk'); AWS.config.region = '******'; exports.handler = async function( ...

Node.js encountered an error due to a self-signed certificate within the certificate chain

I'm encountering an issue with client-side HTTPS requests. An example snippet is as follows: var fs = require('fs'); var https = require('https'); var options = { hostname: 'example.com', port: 443, path: & ...

Retrieve the parent document for every item within a Firebase collection group

Transitioning from an SQL background to document storage, I am currently navigating through a Firebase database structure that looks like this: John (doc) Restaurant Reviews (collection) Review 1 (doc) Review 2 (doc) Paul (doc) Restaurant Reviews ...

Enhance your HTML audio player with added timeline functionality

I'm currently working on incorporating an HTML audio player into my project. I've managed to get the play/pause functionality to work, but now I'm stuck on adding a timeline feature. Additionally, I'm not sure how to implement the play/ ...

Ways to attach jQuery live to the entire window?

tag: I want to trigger specific functions whenever the mouse moves, regardless of its position on the browser window. Currently, I am using the following code snippet: $('html').on('mousemove', function(e) { ... } However, this appr ...

Heroku Woes: Vue-CLI Deployment Woes

I have been facing persistent challenges while trying to deploy my Node.js application with a Vue.js frontend on Heroku. Despite numerous attempts and different configurations, my builds consistently fail due to module resolution errors. Application Infor ...

Ways to transfer the value of a JavaScript variable to a PHP variable

Similar Question: How can I transfer JavaScript variables to PHP? I am struggling to assign a JavaScript variable to a PHP variable. $msg = "<script>document.write(message)</script>"; $f = new FacebookPost; $f->message = $msg; Unfort ...

Title remains consistent | Angular 4

Struggling to change the document title on a specific route. The route is initially set with a default title. { path: 'artikel/:id/:slug', component: ArticleComponent, data: {title: 'Article', routeType: RouteType.ARTICLE, des ...

obtain the text content from HTML response in Node.js

In my current situation, I am facing a challenge in extracting the values from the given HTML text and storing them in separate variables. I have experimented with Cheerio library, but unfortunately, it did not yield the desired results. The provided HTML ...

Converting a string into a TypeScript class identifier

Currently, I am dynamically generating typescript code and facing an issue with quotes in my output: let data = { path: 'home', component: '${homeComponentName}', children:[] }; let homeComponentName = 'HomeComponent' ...

Vue's innate lifecycle hook

I am looking for a way to automatically run a specific function as a beforeMount hook in every component of my Vue project without having to declare it individually. Essentially, I want a default behavior where if the hook is not explicitly stated in a com ...