Why I can use vuex?

倖福魔咒の 提交于 2019-12-17 17:16:55

问题


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?


回答1:


According to this awesome tip from Vuedose

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>



回答2:


Look at the vuex documentation; it describes all the reasons why/when you want to use vuex https://vuex.vuejs.org.

For instance, multiple components require the same information, controlling mutations, validations, etc.




回答3:


Yes, you can do anything without the use of Vuex, but with time, if your application is getting larger then it would be difficult to maintain,

according to vuex documentation,

problem one, passing props can be tedious for deeply nested components, and simply doesn't work for sibling components. problem two, we often find ourselves resorting to solutions such as reaching for direct parent/child instance references or trying to mutate and synchronize multiple copies of the state via events. Both of these patterns are brittle and quickly lead to unmaintainable code.

Hope it answers your question.



来源:https://stackoverflow.com/questions/57710800/why-i-can-use-vuex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!