Is it possible to dynamically invoke a getter with mapGetters in Vue/Vuex?

Here is the template for my component:

<template>
  <section class="stage my-5">

      <div class="stage-heading">
        <h3 class="stage-number mb-4">Stage {{stage}}</h3>
        <h6 class="stage-hrs">Total Hrs: {{totalHours}}</h6>
      </div>

      <div class="stage-courses card text-white bg-info mb-3" v-for="course in courses" :key="course.id">
        <div class="card-header">Stage {{course.stage}}</div>
        <div class="card-body">
          <h5 class="card-title">{{course.title}}</h5>
          <p class="card-text">{{course.creator}}</p>
          <p class="card-text">{{course.hours}} Hours</p>
        </div>
      </div>

    </section>
</template>

This is how the state is defined in my Vuex store:

const state = {
  roadmapStage1: [], 
  roadmapStage2: [],
  roadmapStage3: [],  
};

The getters in my Vuex store are structured like this:

getRoadmapStage1: state => state.roadmapStage1,
getRoadmapStage2: state => state.roadmapStage2,
getRoadmapStage3: state => state.roadmapStage3,

In order to dynamically call one of these getters based on a prop of the component, I have set it up like this:

export default {
  name: "Stage",
  data() {
    return {
      courses: []
    }
  },
   props: ['stage'],
  computed: mapGetters({courses: 'getRoadmapByStage'})
}

I am wondering if there is a way to incorporate the prop into the 'getRoadmapByStage' function, perhaps making it function as getRoadmapByStage${stage}?

My ultimate goal is to ensure that the component re-renders whenever any of the roadmapStage arrays are updated. Thank you!

Answer №1

If you're looking for a way to fetch a specific roadmap based on the stage id or number, consider implementing a getter in your Vuex store. Here's an example of how you can achieve this:

// Define the getRoadmapByStage method in getters.js
getRoadmapByStage: (state) => (stageNumber) => {
    return state["roadmapStage" + stageNumber];
}

Then, in your component, you can utilize this getter to retrieve the appropriate roadmap dynamically:

computed: {
   currentRoadmap() {
      // Pass in the 'stage' prop to fetch the correct map
      // This will automatically update the component if the prop changes
      return this.$store.getters.getRoadmapByStage(this.stage);
   }
}

Answer №2

To define your calculated path attribute, you can use the following code:

computed: {
  path() {
    return this.stage ? this.$store.getters['getPathByStage' + this.stage] : undefined
  },
}

With this method, you will retrieve the path based on the prop value or return undefined if the prop is empty.

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

jQuery: Revealing or concealing several divs upon selection alteration

When I populate a form, I want to display or hide multiple divs based on the OPTION selected in a DROPDOWN. Currently, my code works but the issue is that one div can be hidden or shown by multiple OPTIONS. As a result, these divs keep toggling between hi ...

What is the process for uninstalling Vue CLI 2 from my system?

I am looking to start a new vue project using @vue/cli . It seems that the vue/cli has been updated to version 3. The documentation I found is located at https://i.sstatic.net/iDEJ1.png and I am currently running ubuntu 17.10, attempting to uninstall vue ...

Does angular have a feature comparable to JavaScript's .querySelectorAll()?

I developed an inventory calculator in JavaScript that provides item count based on weight. The calculator has 4 inputs, and now I'm looking to replicate the same functionality using Angular. Is there a method in Angular similar to .querySelectorAll() ...

Visualization of extensive datasets in JavaScript

I'm currently developing a dashboard in JS for displaying sales data plots to users. Can anyone recommend a JavaScript library that meets the following criteria: Capable of plotting a large number of points (ex: 100k or more) Interactive functional ...

Encountered an error while attempting to update data with file upload in Laravel and InertiaJs, response data failed to

I'm currently working on a Single Page Application (SPA) using Laravel 8 and InertiaJs, and I've encountered an issue when trying to update records that have an uploaded file. Storing data works fine, but updating with a file upload seems to be c ...

JavaScript alternative to jQuery's .click() function

After delving into learning JavaScript through jQuery, I realized that while I had mastered the syntax of JS, I hadn't truly grasped the core concepts. This sparked a project where I aimed to replicate jQuery methods using pure JavaScript. I kicked t ...

What is the recommended location to put clearTimeOut?

Attempting the following var timeoutId = setTimeout(function() { if ("comboFilters[Agencies]" in partDic) { var agency = partDic["comboFilters[Agencies]"].substring(1); $('.Agency .dropdown-toggle').html(agency).append(' ...

The alphaMap I'm using doesn't seem to be achieving the desired transparency in my material

I am attempting to create a chainlink surface using 2 textures. The first texture is a standard map that gives the metal links a metallic appearance against a white background (diffuse): The second texture is an alpha map: My attempt to apply both textur ...

Pair each element with an array of objects and add them to a fresh array

Let's consider an array of objects like, const attachmentData = [{name: 'Suman Baidh',attachment: ["123","456"]}, {name: 'John Sigma',attachment: ["789","101112]}, ...

What is the best way to create a Type for approved image formats?

I've been tasked by the client to create a list of supported icon names using TypeScript. However, as a newcomer to TypeScript, I'm finding it challenging to accomplish this. Here is my SVG component containing over 100 SVG icons. CustomIcons.t ...

How can I incorporate a CDN link into the newly updated Next.js App Router?

Exploring next.js has been quite an adventure for me, and I'm impressed with its capabilities. However, being a beginner, I have encountered some challenges. One issue I am currently facing is the difficulty in using Google icons without a CDN link in ...

Could not find reference to Google (error occurred following ajax request)

I encountered an error message when attempting to use the Google Map after making an ajax call. ReferenceError: google is not defined The issue arises when I include the link "<script type="text/javascript" src="http://maps.google.com/maps/api/js?sen ...

Incorporating ng-click functionality within a custom directive

I am trying to create an AngularJS directive that wraps content containing ng-click, but the resulting button does not respond when clicked. Here is a simplified version of the code I attempted: (HTML) <div ng-app="someapp"> <div ng-controll ...

Finding items in the database using their identification numbers

I have a scenario where I am accepting a list of IDs in my request, for example [1,2,3]. How can I use typeorm and querybuilder to retrieve only objects with these IDs from my database? I attempted the following: if(dto.customersIds){ Array.prototype. ...

Storing property data outside of the render method in ReactJS is key for efficient

I have encountered an issue while attempting to map data outside of the render method in my function and return it within the render. The mapping error is causing confusion as I am uncertain about its underlying cause. Below is the function responsible fo ...

Uninitialized NodeJS environment variables

I'm having trouble setting up environment variables. After creating the file and running the server, they appear to be undefined. I am using nodemon and have already tried restarting my server without success. UPDATED .env MONGO_ATLAS_PW = "xxxx"; ...

The interface vanishes upon the integration of TinyMCE into the module

Currently, I am working on a project using Angular-fullstack and attempting to integrate ui-TinyMCE. However, I encountered an issue when I made the following changes: angular.module('academiaUnitateApp') .controller('NewEntryCtrl', ...

What is the process of disabling console log in a Vue template?

Origins of the $log variable: Vue.prototype.$log = console.log Restricted Areas: <template> <!-- Restricted Area 1 --> <div @click="$log"> <!-- Restricted Area 2 --> {{ $log }} <!-- Restricted Area 3 -- ...

How to find the length of an array in Node.js without utilizing JQuery

Is it possible to determine the length of the Dimensions array in nodejs? The array can have 1 or 2 blocks, and I need to write an if condition based on this length. Since this code is inside an AWS-Lambda function, using JQ may not be an option. For exam ...

PapaParse is not properly recognizing the date format

Having trouble creating a chart using JSON data from papaparse, resulting in the following error: c3.js:2100 Failed to parse x '10-18-2018' to Date object I've tried adjusting the date format in the CSV file but haven't had any luck. I ...