Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to call function in component after change value in store?

I have a store with some values and two components. First component its range slider and second its component when i need to call function after red value is changed.

In first component i change slider value and add that in vuex store.

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

How i understand i need to use store.subscribe.watch.rgbColors.red or store.watch.rgbColors.red, its is correct?

And if its correct how call some functions after change value?

like image 258
Drop Avatar asked Dec 14 '22 15:12

Drop


1 Answers

store.subscribe subscribes to mutators. Ala: If you call this.$store.commit('myMutator', payload), your subscriber function would be called with myMutator and payload. This is not what you want.

store.watch will watch some part of the state you define, but its main downside is that you do need to unwatch manually. I believe you would use it like this:

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

// And sometime later
unWatchFn()

You usually don't want to use actual watchers in Vue, because calculating things via computed properties automatically keeps the calculated variable up-to-date. If you need to use watchers, use them on actual components so they automatically get removed and do not cause a memory leak or weird errors. In either case, you will need to make a getter in your store module. Afterwards make either a computed property or a watcher in your component 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>

Edit Vue Template

like image 113
Sumurai8 Avatar answered Dec 18 '22 08:12

Sumurai8