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

What is the method of Vuex state management

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces "what is the method of Vuex state management". In the daily operation, I believe that many people have doubts about the method of Vuex state management. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about "what is the method of Vuex state management?" Next, please follow the editor to study!

EventBus event bus

(figure 2)

A picture is worth a thousand words, as shown in figure 2. Of course, the simplest solution we can think of is to record the subscribers within the component by implementing a centralized event processing center, and notify the subscribers within the relevant components through custom events when collaboration is needed. Of course, the notification can carry payload parameter information to achieve the purpose of data sharing. In fact, Vue itself also comes with a custom event system, and the custom events between Vue components are based on this. For details of api, please participate in the Vue documentation. We can implement the mechanism of EventBus based on Vue itself without introducing new dependencies to reduce the size of bundle. Api uses the following code.

Const vm = new Vue () / / register subscriber vm.$on ('event-name', (payload) = > {/ * execute business logic * /}) / / register subscriber, automatically cancel subscriber vm.$once (' some-event-name', (payload) = > {/ * execute business logic * /}) / / cancel a subscriber vm.$off ('event-name') of an event after one execution [callback]) / / notify each subscriber to execute the corresponding business logic vm.$emit ('event-name',payload) 1, architectural advantages

The advantages of EventBus-based data state management model are found in practice:

The implementation of the code is relatively simple, and the design scheme is easy to understand.

The decoupling between components can be completed in a very lightweight way, turning the strong coupling between components into weak coupling to EventBus.

2. Pain points in practice

Of course, the EventBus scheme also has some shortcomings:

Because the business logic is scattered among multiple component subscribers, the processing of the business logic becomes fragmented and lacks a coherent context.

When reading and maintaining the code, you need to constantly look for subscribers in the code, resulting in interruptions in the understanding of business processes and distractions.

3. Reflection and improvement

When we realize the deficiency in the architecture design of EventBus, we will also Eating our own dog food and implement a set of visual mechanism. Through the analysis of the abstract syntax tree of the code, we can extract the information of subscribers and senders, visually show the relationship between them, and help us understand the problem quickly.

In addition, an improved scheme of [pre-script] is designed for complex business logic. For example, although the active page is made up of multiple RSC components, the requested server interface is still one, which contains all the data of the page's initialization state. At this time, we can uniformly handle the logic of obtaining the data in the front script, and then synchronize it to each RSC component. The way [pre-script] is to extract a global object, including the shared state and business logic. Multiple components depend on this global object, and the architectural design shown in figure 3 is a complement to the EventBus scheme.

(figure 3)

4. Summary

Through the pre-script, we can solve the problem that the complex business is difficult to maintain and understand, but it also brings some risk points such as the need to expose the global object, the risk of being overwritten or modified. After the improvement of the pre-script, we feel more and more clearly what the state management model we need looks like, which is Vuex. Then let's talk about Vuex.

Vuex status Management 1. Background

What is Vuex?

Vuex is a state management model developed specifically for Vue.js applications. It uses centralized storage to manage the state of all components of the application, and uses corresponding rules to ensure that the state changes in a predictable way. Vuex is also integrated into Vue's official debugging tool devtools extension, providing advanced debugging features such as zero configuration time-travel debugging, status snapshot import and export, and so on.

What are the characteristics of Vuex?

Centralized component state management that supports dynamic registration of store

It has a high matching degree with Vue, and the underlying layer is implemented based on the responsive data characteristics of Vue, which maintains the same data processing characteristics as Vue.

After being familiar with Vue, you can quickly get started with Vuex, and the cost of learning is relatively low.

Perfect development experience, official devtools and time-travel debugging, etc., to help developers sort out predictable changes in data

2. Introduce support for Vuex in the platform

Vuex is a general state management framework, how can it be seamlessly integrated into our RSC component architecture? We need to introduce dependency and support for Vuex in the project and add dependency on store in the top-level Vue.

The basic structure of our project:

. └── src ├── App.vue ├── app.less ├── assets ├── component ├── directive ├── main.js ├── stat ├── store └── utils ├── babel.config.js ├── package.json ├── public

2.1 add dependencies

According to the specification, first add the dependency on Vuex to the package.json in our project directory

{"dependencies": {"vuex": "^ 3.0.1"} 2.2 create store object / / store/index.jsimport Vue from 'vue'import Vuex from' vuex'Vue.use (Vuex) export const store = new Vuex.Store ({/ / status data state () {return {}}, getters: {}, mutations: {}, actions: {},}) 2.3 Top-level Vue objects are injected into store

Inject the above creation store object into the top-level Vue object so that all Vue components get the top-level store object through this.$store. In addition, Vuex also provides useful tool class methods (mapState, mapActions, mapGetters, mapMutations) for data sharing and collaboration.

/ / App.vueimport {store} from'. / store'new Vue ({/ / injecting store / / store can be obtained through this.$store in all vue objects managed by Vue,}) 3. Use Vuex to develop RSC components 3.1 RSC own store

We still hope that when developing components, developers only focus on their own presentation and business logic most of the time, and only share their own state to the top-level store when the component is rendered in the activity page. Therefore, the component has its own independent store state management, the state isolation of the module is carried out through the namespace namespace, and then the dynamic store registration is carried out through the registerModule of Vuex within the component's beforeCreate life cycle method.

3.2 StoreMixin injection

You can simplify this process by extracting the public StoreMixin, and you can automatically turn on namespaced: true and extend shortcut methods and attributes for the current namespace. The code is as follows:

/ / store-mixn.jsexport default function StoreMixin (ns, store) {return beforeCreate () {/ / guarantee namespace uniqueness / / developers can generate a unique namespace / / framework through a function that can generate a unique namespace const namespace = isFn (ns)? Ns (this): gen (ns) this.$ns = namespace store.namespaced = true this.$store.registerModule (namespace, store) / / extended shortcut methods and properties this.$state = this.$store.state [namespace] this.$dispatch = (action, payload) = > this.$store.dispatch (`${namespace} / ${action}`, payload) this.$getter = / /. This.$commit = / /...}} / / store.js// the current component has its own storeexport default {/ / component's own status state () {return {}}, mutations: {}, getters: {}, / /... other things} / / code.vue// component external entry module import store from'. / store'export default {mixins: [StoreMixin (/ * namespace*/ 'hello') / * component store * / store)],} 3.3 Namespace conflict How do you solve it?

Because the RSC component will be repeatedly loaded multiple times in an activity, all will cause store modules of the same namespace to be overloaded repeatedly, resulting in module overwriting. How to ensure the uniqueness of namespace? We can, when registering namespace in StoreMixin, determine whether there is the same namespace, and if so, rename the namespace. For example, when you have registered hello as a command space store, re-registering namspace hello will automatically become hello1 and automatically make a distinction. The simple algorithm is implemented as follows

/ / gen.js// generates a unique namespaceconst g = window | | globalg.__namespaceCache__ = g.naming namespaceCacheables _ | | {} / * * generate a unique moduleName, and the name of the same name automatically grows by default * @ param {*} name * / export default function genUniqueNamespace (name) {let cache = g.roomroomnamespaceCachebones _ if (cache [name]) {cache [name] .count + = 1} else {cache [name] = {count: 0 }} return name + (Cache [name] .count = 0?': Cache [name] .count)}

In addition, developers can pass custom functions in store-mixin to generate unique namespace identifiers. For example, the following code sets the namespace according to the routing dynamic parameters in vue-router

Export default {mixins: [StoreMixin ((vm) = > vm.$router.params.spuId), store],} 3.4 the challenge of dynamic namespaces

Because dynamic namespace will bring the problem of uncertainty, the following code example shows that if hello is renamed to hello1, and when you use the mapXXX (mapState, mapMutations, etc.) method in Vuex, you need to pass namespace precisely to get the context of store in the component.

/ / code.vueexport default {mixins: [StoreMixin ('hello', store)], computed: {... mapGetters (' hello', [/ * hello namespace store getter * /]),... mapState ('hello', [/ * hello namespace state property * /]),}, methods: {. MapActions (' hello', [/ * hello namespace actions method * /]) .. mapMutations ('hello', [/ * hello namespace mutations method * /]),},} 3.5 extended Vuex supports dynamic namespaces

How to solve the problem of dynamic namespace in Vuex mapXXX method? The first thing we think of is to set namespace on the this.$ns object of Vue in StoreMixin, so that components mixed with StoreMixin can get namespace dynamically.

/ / store-mixn.jsexport default function StoreMixin (ns, store) {return beforeCreate () {/ / guarantee the uniqueness of namespace const namespace = gen (ns) / / Mount the renamed namespace to the $ns attribute of the current vue object this.$ns = namespace / /.}

Although we can get the namespace of the store in the component through this.$ns, imagine that we can:

/ / code.vueexport default {computed: {... mapGetter (this.$ns, [/ * hello namespace store getter * /]),... mapState (this.$ns, [/ * hello namespace state property * /]),}, methods: {... mapActions (this.$ns, [/ * hello namespace actions method * /]),... mapMutations (this.$ns) [/ * hello namespace mutations method * /]),},}

Unfortunately, this is not an instance of the current Vue at all at this moment, this.$ns 's gorgeous undefined. What are we going to do? JS has many characteristics of functional programming, and functions are also values, which can be passed as parameters. In fact, functions not only have value characteristics, but also have a very important feature is lazy computed lazy computing. Based on this thinking, the mapXX method is extended to support dynamic namespace. Then in the mapXXX method, wait until vm is a component instance of the current Vue before getting the namespace of the current component.

/ / code.vueimport {mapGetters, mapState, mapActions, mapMutations} from 'vuex-helper-ext'export default {computed: {... mapGetters ((vm) = > vm.$ns, [/ * hello namespace store getter * /]),... mapState ((vm) = > vm.$ns, [/ * hello namespace state property * /]),}, methods: {... mapActions ((vm) = > vm.$ns [/ * hello namespace actions method * /]),... mapMutations ((vm) = > vm.$ns, [/ * hello namespace mutations method * /]),},} 3.6 how parent and child components pass dynamic namespaces

I'm sure you've found one of the problems. This.$ns is only available within the components of StoreMixin, so what about the subcomponents of that component? How to solve the problem that the child component gets the namespace of the parent component? At this time, we need to use Vue's powerful mixin system to design a global mixin to determine whether the parent component has a $ns object when the component is created, and set the $ns of the current component to be consistent with the parent component if it exists, and skip it if not.

Function injectNamespace (Vue) {Vue.mixin ({beforeCreate: function _ injectNamespace () {const popts = this.$options.parent; if (popts & & popts.$ns) {this.$ns = popts.$ns; const namespace = this.$ns / / extend shortcut methods and properties for components this.$state = this.$store.state [namespace] this.$dispatch = (action, payload) = > this.$store.dispatch (`${namespace} / ${action}`, payload) this.$getter = / /. This.$commit = / /...}});} / / main.jsVue.use (injectNamespace)

In this way, the component acquires the namespace set by the parent component by default, and with the magic of this mixin, we can extend the design of the mapXXX method a little more elegantly, because the $ns property can be used as the default namespace in the mapXX method. A little more refreshing, keep the style consistent with the official, so that Vuex can be better integrated into our system.

/ / code.vueexport default {computed: {... mapGetter ([/ * hello namespace store getter * /]),... mapState ([/ * hello namespace state property * /]),}, methods: {... mapActions ([/ * hello namespace actions method * /]),... mapMutations ([/ * hello namespace mutations method * /]),} } 3.7 the last complete little chestnut

From the little chestnut below, we can see that for developers, all they have to do is follow the standard Vuex development style, as if nothing had happened. In fact, we have made a lot of efforts internally, and the purpose of architectural design is to make simple things easier and complex things possible.

Store.js RSC components have their own store

Export default {state () {return {mott: 'hello vue'}}, mutations: {changeMott (state) {state.mott =' hello vuex'},},}

Text.vue text sub-component, mapState automatically acquires namespaces dynamically

{{mott}} import {mapState, mapMutations} from 'vuex-helper-ext'export default {computed: {... mapState ([' mott']),}, methods: {... mapMutations (['changeMott']),},}

Code.vue

Import store from'. / store';import text from'. / text';export default {mixins: [StoreMixin ('hello', store)], components: {text}, methods: {/ /.... }} at this point, the study of "what is the method of Vuex state management" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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