What is the best way to trigger a function in a component after a value in the store has

I own a shop that contains various values and two key components. The first component is a range slider, while the second component requires a function to be called after the red value is changed.

In the initial component, I update the slider value and store it in Vuex state.

state: {
    value: 0,
      rgbColors: {
        red: 0
      }
  },

To my understanding, should I use

store.subscribe.watch.rgbColors.red
or store.watch.rgbColors.red? Is this correct?

If so, how can I call certain functions after the value changes?

Answer №1

store.subscribe listens to mutators. For example, if you invoke

this.$store.commit('myMutator', payload)
, your subscriber function will be triggered with myMutator and payload. However, this may not always be the desired behavior.

store.watch allows you to monitor a specific part of the state that you define, but one downside is that you have to manually stop watching. You could utilize it as shown below:

const unWatchFn = store.watch(
  (state) => state.rgbColors.red,
  (newRed) => {
    console.log(newRed)
  }
);

// At some point later
unWatchFn()

In Vue, it's generally advised to avoid using watchers directly because computed properties automatically maintain the calculated values up-to-date. If you must employ watchers, make sure to use them on actual components to prevent memory leaks or unexpected errors. In any case, you will need a getter in your store module. Then, create either a computed property or a watcher in your component based on this getter.

// store.js
export default {
  state: {
    rgbColors: {
      red: 0,
      green: 0,
      blue: 0
    }
  },

  getters: {
    color(state) {
      return state.rgbColors;
    }
  },

  mutations: {
    setColor(state, { red, green, blue }) {
      state.rgbColors.red = red;
      state.rgbColors.green = green;
      state.rgbColors.blue = blue;
    }
  }
};
// SomeComponent.vue
<script>
import { mapGetters } from "vuex";

export default {
  name: "App",

  computed: {
    ...mapGetters(["color"]),

    styling() {
      const { red, green, blue } = this.color;

      return {
        "background-color": `rgb(${red}, ${green}, ${blue})`
      };
    }
  },

  watch: {
    color: {
      deep: true,
      handler(newColor) {
        console.log("Oh, look, a new color!", newColor);
      }
    }
  },

  methods: {
    setColor(red, green, blue) {
      this.$store.commit("setColor", {
        red,
        green,
        blue
      });
    }
  }
};
</script>

https://codesandbox.io/s/z3m6x5or1l

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

Diminishing of the darkness

Imagine a tree adorned with beautiful alpha leaf textures. The intricate pattern of the falling shadow casts a deep darkness on the leaves "below", causing the entire model to appear dark. https://i.sstatic.net/N5ocS.png https://i.sstatic.net/EL5BZ.png ...

Ways to align and fix a button within a specific div element

How can I make the button with position: fixed property only visible inside the second div and not remain fixed when scrolling to the first or last div? .one{ height:600px; width: 100%; background-color: re ...

Encountering a TypeError: relativeURL.replace is not a valid function in Next.js

Why am I encountering this error in my Next.js application? TypeError: relativeURL.replace is not a function. (In 'relativeURL.replace(/^/+/, '')', 'relativeURL.replace' is undefined) Request.js file const API_KEY = process ...

The epoch time indicates a 12-hour difference

I keep encountering an error with the time showing as 12:00 P.M. When I receive a response in epoch time format 1454092200000, it corresponds to 1/30/2016, 12:00:00 AM GMT+5:30 $scope.shipmentDate = moment(1454092200000).format("YYYY/MM/DD hh:mm"); The ...

Can an additional height be added to the equalizer to increase its height?

Is it feasible to append an additional 35px to the height determined by Foundation Equalizer? For instance, if Equalizer computes a height of 350px, I would like to increase it by 35px. This means that the resultant style should be height: 385px; instead ...

What is the best way to change the color of a single line within a

Looking for a way to highlight the selected row using jQuery? Here's a scenario: you have a textarea with multiple lines, and you want to color the line that was clicked by the user. You might be using this code: $(document).on("mouseup", '#scro ...

Resolve the infinite loop issue in Vue.js

I am attempting to verify each comment and reply made by the user, checking if the comment was posted more than 30 minutes ago in order to restrict editing capabilities. However, my current implementation is not functioning correctly and I am encountering ...

Modifying the value of a date picker input using an Angular button

I have an input field with an attached Angular UI datepicker, and I have also added two buttons below to change the date "day by day". Here is the input section on my page: <p class="input-group"> <span class="input-group-addon hidden-xs"> ...

Java Script error persisted in db.system.js.save within MongoDB encountered but remains unresolved

Hello all, I am fairly new to the world of mongoDB and I need some help with performing a search using js stored in mongoDB. Below you will find the javascript code that is stored in my mongoDB database. When attempting the query below: db.eval("dc(cough ...

When navigating back from a child route in history mode, the component is erroneously mounted twice

I have encountered an issue while using vue-router in history mode. When I am on the child route "/dashboard" and refresh the page, the <ccp/> component seems to be mounted twice. The ccp component has console logging in both the created and mounted ...

Validate each element in the looped over input field and update the status for each element

I am currently developing a Vue component and have implemented a v-for loop in the HTML to generate v-text-fields. My goal is to validate that the input in each v-text-field matches one of the elements in an answer array. The current setup is as follows: & ...

Understanding the functionality of AngularJS UI-Router

I'm trying to wrap my head around the purpose of the parent attribute within the state directive in UI-Router. Let's consider this code snippet: $stateProvider .state('base', { abstract: true, url: '', templateU ...

What is the best way to assign a unique ID to every <td> element within a table using React Js?

Hello everyone. I am currently working on assigning unique ids to each td in a table based on data received through an API. This is what my code looks like so far. CodeSandbox const assignIdsToTableData = (data) => { var items = Object.values(data)[0 ...

Dealing with Errors in Promises: A guide

Recently I started learning about Promises and how to handle errors using promise Catch blocks. I have a question - is there a way to streamline error handling by using only one catch block instead of two in my code? I would appreciate any help or sugges ...

What is causing this JSON to malfunction in Internet Explorer?

Everything is functioning well on Chrome and other browsers except for IE. Below is an example to illustrate: (specifically referring to IE 8, unsure about compatibility with IE 9) Upon running the JSON request, I encountered an error stating "Object exp ...

Mapping geographic coordinates with a null projection using D3

With d3.geo.path having a null projection due to TopoJSON already being projected, it can be displayed without any additional transformation. My goal is to plot data in the format of [longitude, latitude] on a map. Here is a simplified version of my code: ...

Error: Discord bot encountered a TypeError while attempting to access the property 'id' of an undefined value

After revisiting a previous Discord bot package designed to track website updates, I encountered an issue. The code was originally scraped and last edited about 8 months ago with success. However, upon running node index.js, the following error occurred. ...

React - CSS Transition resembling a flip of a book page

As I delve into more advanced topics in my journey of learning React and Front Web Dev, I discovered the ReactCSSTransitionGroup but learned that it is no longer maintained so we now use CSSTransitionGroup. I decided to create a small side project to expe ...

Mocking HTTP requests during integration testing of a JavaScript application executed with Selenium

When running my Vue SPA integration tests with webdriverio and cucumberjs, the application makes requests to an api-server to get data. I am looking for a way to modify or stub the data returned from the api-server in my tests without directly affecting t ...

JavaScript hard-coded object functions as an argument, however it does not reference the global object

Recently, I encountered a strange issue while working with JQuery Flot. Initially, my code looked like this: var plot = null; function initPlot () { plot = $.plot("#graph", myData, { /* my options here */ }); } and everything was functioning correc ...