Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use Vuex?

Now I start to learn vue, and I'm creating SPA for editing database. Now I can't understand where I should use a Vuex. I can use props and $emit everywhere and it can help me find needed parameter. So for what case I should use Vuex?

like image 350
Andrey Kadnikov Avatar asked Aug 29 '19 13:08

Andrey Kadnikov


1 Answers

According to this awesome tip from Vuedose blog

Vue.js 2.6 introduced some new features, and one I really like is the new global observable API.

Now you can create reactive objects outside the Vue.js components scope. And, when you use them in the components, it will trigger render updates appropriately.

In that way, you can create very simple stores without the need of Vuex, perfect for simple scenarios like those cases where you need to share some external state across components.

For this tip example, you’re going to build a simple count functionality where you externalise the state to our own store.

First create store.js:

import Vue from "vue";

export const store = Vue.observable({
  count: 0
});

If you feel comfortable with the idea of mutations and actions, you can use that pattern just by creating plain functions to update the data:

import Vue from "vue";

export const store = Vue.observable({
  count: 0
});

export const mutations = {
  setCount(count) {
    store.count = count;
  }
};

Now you just need to use it in a component. To access the state, just like in Vuex, we’ll use computed properties, and methods for the mutations:

<template>
  <div>
    <p>Count: {{ count }}</p>
    <button @click="setCount(count + 1);">+ 1</button>
    <button @click="setCount(count - 1);">- 1</button>
  </div>
</template>

<script>
  import { store, mutations } from "./store";

  export default {
    computed: {
      count() {
        return store.count;
      }
    },
    methods: {
      setCount: mutations.setCount
    }
  };
</script>
like image 59
Boussadjra Brahim Avatar answered Oct 01 '22 21:10

Boussadjra Brahim