Original text: markus.oberlehner.net/blog/should…

The first thing most people want to know when they first start using Vuex is, what kind of data do you want to store in it? In trying to answer this question, many people (including me) first come to the “all in” stage. But after the first hurdle, you quickly realize that this isn’t the perfect solution for managing data in vue.js.

In this article I will attempt to answer questions such as “when is Vuex a hand-to-hand solution” and “when is it better to do it another way?”

I. First, why Vuex?

Vue.js gives us reactive data properties — a powerful way to handle state out of the box, as well as pass data to child components.

export default {
  name: 'MyComponent',
  data() {
    return {
      someValue: 'Hello World'}; }},Copy the code
<template>
  <div class="MyComponent">
    <some-component :some-value="someValue"></some-component>
  </div>
</template
Copy the code

If you’re developing a fairly simple application, or if all you have to do is replace some (originally server-side rendering) parts of your application with some magic of vue.js, then you really don’t need Vuex at all.

On the other hand, if you’re developing a large, single-page application, you might have two very different places in your application that need the same data. This is where centralized state management tools like Vuex come in handy from time to time.

II. Reasons for storing data in Vuex

So what are the reasons for storing data in a centralized Vuex store?

2-1. Data must be accessible to multiple (independent) components

The first use case for putting data in a centralized store like Vuex is that the data must be accessed in multiple places in the application, and these places are likely to be components that are unrelated (not as simple as a parent component or a child component). An example is to use some custom Settings to configure the look and feel of an application or what date format should be used in a specific place.

2-2. Centralized API/data acquisition logic

As an example, try a time-tested to-do application: you request a list of all the to-do items from an API, and you display all items in chronological order, and there are pages that display only specific categories within them. With Vuex, you can grab all of your To-do items once, store them in the Store, and then access them in every component of your application, even if they’re distributed across different routes. Another approach is To request a specific to-do item when the user navigates To a route of a specific class; Depending on the nature of the application, that might also make sense.

2-3. Persistent application status of the client

Managing persistent state with Vuex in the browser is easy thanks to vuex-PersistedState, a vue.js plug-in. This makes it easy to handle complex situations where users stay offline.

III. Reasons for not storing data in Vuex

If you have decided to use Vuex to manage state in your application, then each time you add a new component, you have to make a decision about whether to store its state in Vuex. If you’re new to Vuex, you might be tempted to use it for just about everything — so why not?

3 to 1. The complexity

Although Vuex is simpler than its peers, it is still more cumbersome than using component local state directly. You need to evaluate whether the additional complexity is worth the benefits of a centralized state.

3-2. Maintenance costs

Using Vuex in components always means there is a maintenance cost. For this reason, I recommend that you use the local state of the component as the default, and only use Vuex selectively when there is a good reason to do so.

Alternatives to iv. Vuex for storing data

Having said that, what are the alternatives when Vuex is not the best solution?

4-1. Props for passing down

Often the simplest way is the best way. If you can solve a problem with props passed from parent to child, you should definitely do that.

4-2. provide / inject

A little-known vue.js feature is provide/inject. It is used in scenarios where data needs to be passed from an ancestor component to all its descendants.

Basic examples from official documentation:

// Parent component provides 'foo'
var Provider = {
  provide: {
    foo: 'bar'
  },
  // ...
}

// Descendant components inject 'foo'
var Child = {
  inject: ['foo'],
  created () {
    console.log(this.foo) // => "bar"
  }
  // ...
}
Copy the code

A typical example is an Accordion component, which might consist of a main AppAccordion component, several AppAccordionItem child components representing each collapsible, and an AppAccordionBody child component representing the body of the collapsible. Provide/inject makes it possible to pass data from the master component to the grandson component. This pattern is simpler and more efficient than using Vuex in the case where the components depend on each other directly (AppAccordionBody cannot be used without the AppAccordion component).

4-3. Get data from API/Apollo

Let’s review a positive example of Vuex mentioned in 2-2: a to-do application with multiple categories. Rather than fetching and storing a user-owned (unfinished) to-do item at once, a better implementation might be To just fetch the first 20 renderings for the entry page. If the user navigates to a specific category page, a new request is triggered to get the first 20 entries of the corresponding category from the API. If a user accesses a previously opened category, we can either request fresh data again, or we can implement some kind of caching (Apollo provides a caching mechanism out of the box).

GraphQL is a query language created by Facebook to describe complex data models. It is a specification for both front and back end data queries. Apollo is a collection of full stack solutions based on GraphQL. The corresponding lib is provided from the back end to the front end to make the development of GraphQL more convenient; One plug-in available for Vue is vue-apollo.netlify.com/

4-4. portals

At first glance, the PortalVue plug-in doesn’t seem to have anything to do with state management. However, in some cases a portal can access the state of a component directly, rather than through a centralized store. A typical example might be a modal dialog box, used to confirm that the user did not hit the delete button by mistake:

<template>
  <button class="AppDeleteButton" @click="modal = true">delete<portal to="modals" v-if="modal">
      <app-modal>You have a plan, don't you?<button @click="delete(item.id)">right</button>
        <button>Forget it</button>
      </app-modal>
    </portal>
  </button>
</template
Copy the code

You can see that when the AppDeleteButton component is clicked, it displays the modal it contains. Instead of separating the write button from the popover and accessing the ID data globally through the Store, in this example the AppDeleteButton’s internal property values are accessed directly from the Model component.

V. The picture you asked for

To facilitate decision-making, the above content is summarized as the following figure:

VI. Conclusion

Remember that there is no one-size-fits-all approach to software development. Everything has a context, and there are many articles in which a particular technique works well in a particular situation, but may not work well for your particular use case.

Be open to new (and old) ways of doing things, and don’t be afraid to experiment — even if some ways of sharing state in your app don’t work, at least you’ve learned when not to use them, and it’s always a good time to refactor your code.






–End–






Search fewelife concern public number reprint please indicate the source