Creating a component that responds to changes in the state data

In my Vue application, I have the following layout:

App.vue

<template>
  <div id="app">
    <Progress />
    <router-view />
    <Footer />
  </div>
</template>
<script>
import Footer from "@/components/Footer";
import Progress from "@/components/Progress";

export default {
  components: {
    Footer,
    Progress,
  },
};
</script>
Code snippet for progress bar:

<template>
  <section>
    <div class="columns is-mobile pt-6" v-show="progressBar()">
      <div class="column is-three-fifths is-offset-one-fifth">
        <progress
          class="progress is-success"
          :value="(progress.count / 9) * 100"
          max="100"
          >{{ (progress.count / 9) * 100 }} %</progress
        >
      </div>
    </div>
  </section>
</template>
<script>
import { mapGetters } from "vuex";
export default {
  name: "Progress",
  methods: {
    progressBar() {
      console.log(this.progress.status);
      if (this.progress.status == false) {
        return false;
      }
      return true;
    },
  },
  computed: mapGetters({
    progress: "getProgressBar",
  }),
};
</script>

And Vuex store for the progress bar.

src/store/modules/ProgressBar.js

const state = {
  count: 1,
  status: false,  
};

const getters = {
  getProgressBar: state => state,
};

const actions = {
};

const mutations = {
  setProgressBar(state, value) {
    state.status = value;
  },
  progressIncrease(state) {
    state.status = state.status + 1;
    console.log(state.status);
  }
};

export default {
  state,
  getters,
  actions,
  mutations,
};
My route component Basics.vue loads from the route /basic;

<template>
  /* code for form layout goes here*/
</template>
<script>
export default {
  name: "Basics",
  methods: {
    toNetworks() {
      this.$router.push({ name: "Location" });
      this.$store.commit("progressIncrease");
    },
    /* other codes to handle input */
  },
  created(){
    this.$store.commit("setProgressBar", true);
  }
};
</script>

With the above setup, I am trying to increment the variable count in the state as the form steps increase and show the progress bar accordingly.

The states are being set correctly and I can increment it with the commit. However, the progress bar component is not reacting to the updated data in the state.

I am aware that the mapGetter method is called only once when the <Progress/> component is loaded in the App.vue component.

Is there a method or way to make the <Progress/> react to changes on the data in the state that are made from the router component?

Answer №1

When implementing the progressIncrease mutation, ensure that you are updating the correct state (status - which is a boolean). You will need two getters to access both the status and count states as intended. Here's how your mutations and getters should look:

const mutations = {
  progressIncrease(state) {
    state.count = state.count + 1;
  }
};

const getters = {
  count: state => {
    return state.count;
  },
  status: state => {
    return state.status;
  }
}

To efficiently access these states in your component, you can use mapGetters like this:

computed: {
  ...mapGetters([
    'count',
    'status',
  ])
}

Simply replace this.progress.status with "this.status" and this.progress.count with "this.count". You can also utilize aliases if desired. Further information on getters can be found here

Alternatively, it is recommended to use mapState when dealing with state retrieval instead of modification, following best practices illustrated in the Vue documentation example linked above.

With mapState, your implementation will look like this:

 computed: mapState({
    count: state => state.count,
    status: state => state.status,
 })
 

You can now easily access the states using this.count and this.status. Feel free to use aliases for added customization. For more details on mapState usage, refer to this resource

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

When Vue 3 is paired with Vite, it may result in a blank page being rendered if the

Issue with Rendering Counter in Vite Project After setting up a new project using Vite on an Arch-based operating system, I encountered a problem when attempting to create the simple counter from the Vue documentation. The element does not render as expec ...

Creating a search dictionary in MongoDB for text validationDiscover how to implement a search dictionary in MongoDB

I have a project in mind to create a spell-check dictionary for text verification. The dictionary contains 20,000 words. With my Meteor application, the goal is to input the text, split it into words, and verify each word against the dictionary. However, ...

Using Node.js to download and install npm packages from the local hard drive

Is there a way to add an npm package to my Node.js project from my hard drive? It seems like the admin at work has restricted access to npm. I managed to install npm, but whenever I attempt to run "npm install express" in the command line, I keep getting ...

Utilizing AngularJS to access one route's resolve data from another resolve

I am working on a route resolve that includes the following functions: resolve: { user: function($route, User){ return User.find($route.current.params.id); }, stats: function($route, Stats) { /* asynchronous stat retrieva ...

Encountering an HTTP 400 Bad Request error while trying to upload a file through an AJAX post request to a

I'm encountering an issue whenever I try to upload a file that is not in .txt format. Text files work fine, but any other type of file results in an error. It seems like this problem didn't exist a year ago because the code went through extensive ...

Using Leaflet to beautify categorical json information

As a beginner in coding, I must apologize if a similar question has already been asked. I've spent days searching but haven't found the right combination of terms to find examples for my scenario. I am exploring various small use cases of differ ...

Error message occurs when creating a pie chart with invalid values for the <path> element in Plottable/D3.js

For those who need the code snippets, you can find them for download here: index.html <!doctype html> <html> <head> <meta charset="UTF-8"> <!-- CSS placement for legend and fold change --> </head> <body ...

Function for Duplicating jQuery Events

I'm currently facing an issue where every time the browser is resized, a function is triggered. This function can turn a side panel into an accordion if the screen width meets certain criteria, or it can just display as an open side panel on larger sc ...

Implementing a delay of X seconds after a click event in JQuery: A step-by-step guide

Is there a way to delay the triggering of a click event after one has been recently triggered? I am facing an issue on my website where users can click multiple times on the "dropdown icon" and cause it to toggle the slide effect multiple times. What I wan ...

Troubleshooting problem with JSON array value in Petfinder's AJAX request

$(document).ready(function(){ var url = 'http://api.petfinder.com/shelter.getPets?key=99392cbf55ee6b2f9b97ed375eca907d&id=WI22&status=A&output=full&format=json'; $.ajax({ type : 'GET', ...

Having trouble with input functionality on iPad due to a CSS, LI, div, or clipping issue?

https://i.sstatic.net/muMSG.png One challenge I am facing is related to several inputs housed within an LI and div that are sortable using jQuery. The problem arises specifically on the iPad when attempting to click into the inputs to enter information - ...

Creating a Javascript countdown timer that remains active even when the page is refreshed

I'm in the process of developing an Auction website but facing challenges in creating a fixed countdown timer for all users. I attempted to implement Ajax but found it to be unhelpful. Below is the code snippet I have currently: <!DOCTYPE html> ...

Express JS failing to detect the current environment

I have organized my application folder structure in the following way. app/ config/ app.js env.js server.js Every time I try to run my app.js file, it displays "server started at undefined". Here is a link to the code snippet: Gist Cod ...

Ensuring precise accuracy in JavaScript; transforming 0.5 into 0.5000

My current challenge involves converting every fraction number to n decimal places in JavaScript/Node.js. However, I've encountered a roadblock as it appears impossible to convert 0.5 to 0.5000. This discrepancy is causing my test cases that anticipat ...

Copy the contents of matrixA into matrixB and append a new element to each array within matrixB

I want to copy the values from matrixA into matrixB and then add a new element to each array in matrixB. let number = 100; matrixA = [ [1, 2], [3, 4] ]; matrixB = [ [1, 2, 100], [3, 4, 100] ]; Currently, my code looks like this: for (let ...

Changing the URL parameters to accommodate a specific query

Currently, I have set up the route as follows: app.get("/employees", (req, res) => { data.getAllEmployees().then((data) => { res.json(data); }).catch(function(err) { console.log("An error was encountered: " + err); }); }) ...

Encountered a CSS error while trying to compile the project with npm build

When attempting to build the project, I encountered a postcss error. After some debugging, I discovered that the imports below were causing the issue: @import "@material/button/dist/mdc.button.min.css"; /*material text box css*/ @import "@material/float ...

Issues encountered when attempting to use @app.route without redirection

I have a function that works perfectly when I redirect to another page with @app.route('/results'), but I'm having trouble making it work on the same page without reloading: @app.route('/') def static_file(): return app.send_s ...

"Enhance your website design with the powerful features of

My goal is to 1) align radio buttons to the left 2) reduce the vertical spacing between label and radio button texts as well as between each text In the provided example, the radio button texts are currently centered with excessive space between them, whi ...

How to hide bullet points in a list when the links are hidden, utilizing either Jquery or CSS

In my attempt to hide bullet points from a list when links are hidden, the first and second links have been hidden using backend code in C#. I am trying to make sure that the bullets are only displayed if there are actual links present. <div class="l ...