Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to create Vuex store

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how to create Vuex store". Friends who are interested might as well take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to create Vuex store.

State and the birth of components

Since the birth of the three frameworks, their two common capabilities have thoroughly cracked down on Jquery. These two abilities are:

Data driven view

Componentization

Data-driven views make us bid farewell to the era when we can only update pages by operating DOM. We no longer need to use layers of find to find DOM and then modify its properties and content every time we update the page. We can do this by manipulating the data.

Of course, in the eyes of our front end, data can basically be understood as storing variables of various data types. After the emergence of the concept of data-driven, some variables have been given a special meaning.

First of all, there are ordinary variables, which are no different from the JQ era and are only used to store data. In addition, there is a class of variables, they have a responsive effect, these variables are bound to the view, when the variable changes, the view bound to these variables will also trigger the corresponding update, which I call state variables.

The so-called data-driven view, strictly speaking, is that state variables are driving the view. With the popularity of Vue,React, the focus of front-end developers has gradually shifted from operating DOM to operating data, and state variables have become the core.

State variables, now people seem to prefer to call them states. We often talk about the state, state management, in fact, this state refers to the state variable. The state mentioned below also refers to the state variable.

With the state, the components also come.

In the JQ era, the front end of a page is a html, there is no concept of "components", for the common parts of the page, it is not too difficult to implement elegant reuse. Fortunately, the three frameworks bring a very mature component design, it is easy to extract a DOM fragment as a component, and components can maintain their own state, higher independence.

An important feature of components is that these internal states are isolated from the outside. The parent component cannot access the state within the child component, but the child component can access the passed status (Props) displayed by the parent component and automatically respond to changes.

This feature can be understood to mean that the state is modular. The advantage of this is that there is no need to consider that the state of the current setting will affect other components. Of course, it is not realistic to completely isolate the state of components, and there is bound to be the need for multiple components to share state. The solution in this case is to extract the state to the nearest parent component of these components and pass it down through Props.

The above shared-state solution is generally fine and is an officially recommended best practice.

But if your page is complex, you will find that it is still inadequate. For example:

The level of the component is too deep and the state needs to be shared, which is passed layer by layer.

Child components update a state, there may be multiple parent components, sibling components share, it is difficult to implement.

In this case, continue to use the "extract state to parent component" method, you will find it very complicated. And as the number of components increases and the level of nesting deepens, this complexity becomes higher and higher. Because there are many associated states and complex transmission, it is easy to have problems such as an inexplicable update of a component and whether a component is updated or not, and exception troubleshooting will be difficult.

In view of this, we need a more elegant solution to deal with this complex situation.

Do you need state management?

As we mentioned in the previous section, with the complexity of the page, we encountered a thorny problem in the implementation of sharing state across components.

So is there a solution? Of course, thanks to the efforts of the community leaders, there is more than one plan. But these solutions all have a common name, which is what we discussed very hotly two years ago-state management.

State management, in fact, can be understood as global state management, where the state is different from the internal state of the component, it is maintained independently of the component, and then in some way associated with the components that need the state.

State management has its own implementation scheme. Vue has Vuex,React and Redux,Mobx, and of course there are other options. But they all solve a problem, that is, the problem of cross-component state sharing.

I remember that in the past two years, because of the popularity of the concept of "state management", it seems to have become an indispensable part of application development. Take Vue as an example, to create a project, it is necessary to introduce Vuex for state management. But many people do not know why, when and how to use state management, just blindly follow the trend, so there are many examples of abuse of state management.

Seeing here, you should know that state management is not necessary. It is basically clear why it appears and what problems it wants to solve. If you don't understand, please pause and read it again from the beginning. Do not think that the background of the birth of a technology solution is not important, if you do not understand what problem it is to solve, then you can not really play its role.

The author of Redux has a famous saying: if you don't know if you need Redux, you don't need it.

Well, if you're using state management, or if you need to use state management to help you solve your problem, let's move on.

Vuex

Vue is widely used in China, especially in small and medium-sized teams, so the first state management solution that most people come into contact with should be Vuex.

So how does Vuex solve the problem of cross-component state sharing? Let's explore together.

Create store

As we mentioned above, for general component sharing state, the official recommendation is to "extract the state to the nearest parent component." Vuex is a step further, extracting all states to the root component so that any component can access it.

You may ask: doesn't this expose the state as a whole? Won't the advantages of modularity be completely eliminated?

Actually this is not so. The main purpose of Vuex is to make these states accessible to all components, completely avoiding situations where child component states are inaccessible. Vuex puts all the state data on one object, following the principle of a single data source. But this does not mean that the state is stacked. Vuex implements its own modularization scheme on this single state tree.

Don't worry, let's take a look at how to use Vuex step by step.

Vuex exists as a plug-in to Vue, first npm installation:

$npm install-save vuex

After installation, we create a new src/store folder and put all the Vuex-related code here.

Create a new index.js and write the following code. The main purpose of this code is to load the plug-in Vuex with the Vue.use method, and then export the configured Vuex.Store instance.

Import Vue from 'vue'import Vuex from' vuex'// installs the plug-in Vue.use (Vuex) export default new Vuex.Store ({state: {}, mutations: {}, actions: {}, modules: {}})

The example exported above is commonly referred to as store. A store contains stored states (state), functions to modify states (mutation), and so on, and all states and related operations are defined here.

The last step is to mount the store instance exported above to Vue in the entry file:

Import store from'. / store'new Vue ({el:'# app', store: store})

Note: mounting this step is not necessary. The purpose of mounting this step is only to facilitate access to our exported store instance through this.$store in the .vue component. If it is not mounted, it is the same for direct import.

Single data source (state)

In the last step, we created an instance of store with the constructor Vuex.Store, and you at least know how to use Vuex. In this step, let's look at the specific configuration of the Vuex.Store constructor.

The first is the state configuration, whose value is an object that stores state. Vuex uses the principle of a single state tree to place all states on this object to facilitate subsequent state positioning and debugging.

For example, we have an initial state app_version to represent the version, as follows:

New Vuex.Store ({state: {app_version: '0.1.1'}})

Now to get it in the component, you can do this:

This.$store.state.app_version

But this is not the only way to get it, it can also be like this:

Import store from'@ / store' / / @ represents the src directory store.state.app_version

Why emphasize this point? Because many friends think that Vuex can only be operated through this.$store. In a non-component, for example, if you want to set the state of a Vuex in the request function, you don't know what to do.

In fact, there are more elegant ways to get state in components, such as the mapState function, which makes it easier to get multiple states.

Import {mapState} from 'vuex'export default {computed: {... / / other calculation attributes... mapState ({version: state = > state.app_version})}} status update method (mutation)

The state in Vuex is different from the state in the component and cannot be modified directly in the way of state.app_version='xx'. Vuex stipulates that the only way to change the status is to submit a mutation.

Mutation is a function with the first argument state, which changes the state of the state.

The following defines a mutation called increment to update the state of count in the function:

New Vuex.Store ({state: {count: 1}, mutations: {increment (state, count) {/ / change status state.count + = count})

Then trigger increment in the .vue component:

This.$store.commit ('increment', 2)

In this way, views that are bound to count are automatically updated.

Synchronous update

Although mutation is the only way to update status, it actually has one limitation: it must be synchronized.

Why do I have to update synchronously? Because in the development process, we often track changes in state. The common method is to debug in the browser console. The use of asynchronous state update in mutation will also make the state update normally, but it will cause the developer tools to be unable to track the state changes sometimes, which makes it difficult to debug.

In addition, the positioning of Vuex to mutation is to change the state, just change the state, and don't participate in anything else. The so-called dedicated work, which also helps us avoid mixing the change state with our own business logic, and standardizes the function function.

What if you do need asynchronous updates?

Asynchronous update

Asynchronously updating status is a very common scenario, such as the data requested by the interface is to be stored, that is, asynchronous update.

Vuex provides action for asynchronously updating status. Unlike mutation, action does not update status directly, but indirectly by triggering mutation. So even using action does not violate the principle that the only way to change state is to submit a mutation.

Action allows you to do some side effects before actually updating the status, such as async, data processing, conditional submission of different mutation, and so on. Look at an example:

New Vuex.Store ({state: {count: 1}, mutations: {add (state) {state.count++}, reduce (state) {state.count--}}, actions: {increment (context) Data) {axios.get ('* *) .then (res = > {if (data.iscan) {context.commit ('add')} else {context.commit (' reduce')})}})

Trigger action in the component:

This.$store.dispatch ('increment', {iscan: true})

These are how action is used. In fact, the main function of action is to request the interface, get the required data, and then trigger mutation to modify the status.

In fact, this step can also be implemented in the component. I have seen some scenarios, it is common to write a request method in the component, when the request is successful, directly through the this.$store.commit method to trigger mutation to update the status, do not use action at all.

Is action dispensable?

No, action is really needed in a particular scenario, which will be discussed in the next article.

State Modularization (module)

As mentioned earlier, Vuex is a single state tree, and all states are stored on a single object. At the same time, Vuex has its own modular scheme.

To prevent states from piling up and becoming bloated.

Vuex allows us to split store into modules (module), each with its own state, mutation, and action. Although the state is registered in the root component, module segmentation is supported, which is equivalent to a "state component" that is on a par with the page component.

In order to distinguish, we call the segmented module as the sub-module, and the global module as the global module.

Let's look at the basic usage:

New Vuex.Store ({modules: {user: {state: {uname: 'ruims'}, mutation: {setName (state, name) {state.name = name})

The user module is defined above, including a state and a mutation. The methods used in components are as follows:

/ / access status this.$store.state.user.uname// update status this.$store.commit ('setName')

You have found that the state that accesses the sub-module is through this.$store.state. [module name] if you access it in this way, triggering mutation is the same as the global module.

The principle of action is consistent with that of mutation, so we won't go into details.

Namespace

As mentioned above, the submodule triggers mutation and action consistent with the global module, so it is assumed that there is a mutation named setName in both the global module and the submodule. Which mutation will be executed when triggered in the component?

After testing, it will be carried out. The official saying is: in order for multiple modules to respond to the same mutation or action.

In fact, the official compatibility, I have not encountered the actual application scenario, but caused a lot of trouble because of the wrong trigger caused by the same name mutation. Perhaps the authorities were aware of this problem, and the index later made a modular solution for mutation and action.

This scheme is the namespace.

The namespace is also very simple. Add a namespaced: true configuration in the sub-module to enable it, such as:

New Vuex.Store ({modules: {user: {namespaced: true, state: {})

When the namespace is opened, triggering mutation becomes:

This.$store.commit ('user/setName')

You can see that the submission parameter has changed from'[mutation]'to'[module name] / [mutation]'.

Modular slot point

Above we introduced the modularization scheme of Vuex, which divides a single state tree store into multiple module, each responsible for storing and updating the state of this module.

Modularization is necessary, but the scheme of this module always feels a little awkward to use.

For example, the overall design is to divide the store into modules, and the modules contain state,mutation,action.

According to the normal understanding, the state under the user module should be like this:

This.$store.user.state.uname

But the actual API looks like this:

This.$store.state.user.uname

This API seems to be divided into separate modules in state. I haven't seen the source code, but in terms of experience, it's not a twist.

In addition to state, the default registration of mutation,action in the global design is also very awkward.

First of all, it is officially said that multiple modules respond to the same mutation or action, and this feature has not yet found an application scenario. And make sure that the naming is unique when not equipped with namespace, otherwise it will cause false trigger.

Second, after using namespace, the trigger mutation looks like this:

This.$store.commit ('user/setName')

This obviously deals with the parameters separately, why not:

This.$store.user.commit ('setName')

The overall feeling is that Vuex modularization is not thorough enough.

Why complain?

The slack mentioned above is not for the sake of complaining. The main reason is that there is still room for optimization.

For example, the this.$store.commit function can trigger any mutation to change the state. If a component is complex and needs to operate the state of multiple sub-modules, it is difficult to quickly find out which sub-modules are operated by the current component, and of course it is not easy to make permission regulations.

What I hope is that, for example, if component A uses the state of two sub-modules, b and c, and is not allowed to operate other sub-modules, then module import can be used first, such as:

Import {a, b} from this.$storeexport default {methods: {test () {alert (a.state.uname) / / access status a.commit ('setName') / / modify status}

In this way, it is clear to import, query and use according to the module.

At this point, I believe you have a deeper understanding of "how to create Vuex store". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report