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

Use cases for Vuex

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article will explain the use cases of Vuex for you in detail. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

I. brief introduction

Let's take a look at a more professional introduction to Vuex:

Vuex is a state management mode of an application developed specifically for Vue. 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.

In short, Vuex uses a form similar to a global object to manage the common data of all components. If you want to modify the data of this global object, you have to modify it in the way provided by Vuex (you can't modify it in your own way).

Second, advantages

Vuex state management is different from using traditional global variables:

The state storage of Vuex is responsive: that is, when your component uses the state of the Vuex, once it changes, all associated components will automatically update the corresponding data, making it easier for developers.

The state of Vuex cannot be modified directly: if it is a global object variable, it is easy to change, but it cannot be done in Vuex. If you want to change it, you have to use the only way that Vuex provides: commint mutations to implement the change. The advantage of this is that it is convenient for us to track each state change, which is very useful when debugging in the development process.

Third, use step 1. Install Vuexnpm install vuex-- save2. Reference Vueximport Vue from 'vue'import Vuex from' vuex'Vue.use (Vuex) 3. Create a warehouse Store

To use Vuex, we create an instance store, which we call a repository, and use this repository store to manage our state.

/ / create a storeconst store = new Vuex.Store ({}); fourth, include modules

State: defines the data structure of the application state, where you can set the default initial state.

Getter: allows components to retrieve data from store, and the mapGetters helper function simply maps the getter in store to local evaluation properties.

Mutation: is the only way to change the state in store and must be a synchronization function.

Action: used to submit the mutation instead of changing the state directly, and can include any asynchronous operation.

Module: store can be split into modules (module). Each module has its own state, mutation, action, getter, or even nested submodules

Vuex acts like a global object. Vuex uses a single state tree and an object State contains all the states at the entire application level. You can understand that these states are a bunch of global variables and data.

1. State

Suppose we have a global state count with a value of 5. Then we can define it as key and value in the state object, which can be used by us as global state. As follows:

/ / create a store const store = new Vuex.Store ({/ / state storage application layer status state: {count:5 / / total: 5}}); 2. Getters

It can be considered that getters is the computational attribute of store, which is similar to computed, which filters and modifies the data in state.

If we want to derive a new state newCount from state.count, it is appropriate to use our getters.

Getters accepts state as its first parameter

Const store = new Vuex.Store (status of {/ / state storage application layer state: {count:5 / / total: 5}, getters: {newCount:state = > state.count * 3}})

Get the {{newCount}} method in the component:

Export default {computed: {newCount () {return this.$store.getters.newCount;}; 3. Mutations

Vuex provides us with the only way to modify the state in the repository store by submitting the mutation, which must be a synchronization function

We define a function called increment in mutations, and the function body is where we want to change it.

Will accept state as the first parameter, and the second is a custom pass parameter

Const store = new Vuex.Store ({/ / state storage application layer status state: {count:5 / / Total: 5}, / / mutations is the only way to modify the data in state mutations: {increment (state,value) {state.count + = value;})

When we submit the commit, the first parameter "increment" corresponds to the increment method in mutations, and the second parameter is the custom value. For example:

Methods: {getVal (event) {/ / get the value of the current key let value = event.target.dataset.value; / / submit a mutation this.$store.commit named increment ("increment", value) through commit;}}

Get the {{count}} method in the component:

Export default {computed: {count () {return this.$store.state.count;}; 4. Action

Used to submit the mutation instead of changing the state directly, and can include any asynchronous operation

This process can only be operated through action= > mutations= > states. The specific steps are as follows:

Export default new Vuex.Store ({/ / store data state: {obj: {},}, / / 4. Deal with mutations through the method in commit mutations: {getParam (state, Object) {/ / 5. Modify the data in state state.obj = Object}}, / / 2. Accept the method and parameter actions passed by dispatch: {getParamSync (store, Object) {/ / handle asynchronous operation setTimeout (() = > {/ / 3. A mutation / / action function named getParam is submitted through commit to receive an instance object of store, so you can call store.commit to submit a mutation store.commit ('getParam', Object);}, 1000)}})

Then we can just call it in the component.

Methods: {getVal () {let name= 'xia'; let age=' 26; let sex= 'man'; / / 1. Pass the method getParamSync and several parameters {name,age,sex} to actions this.$store.dispatch ('getParamSync', {name,age,sex})}} 5. Modules through dispatch

As the complexity of the project increases, in order to facilitate the management of Vuex, it is generally divided into different modules (Module) according to function, which is convenient for future management. Each module has its own state, mutation, action, getter or even nested submodules

Import Vue from 'vue'import Vuex from' vuex'import state from'. / state'import mutations from'. / mutations'import actions from'. / actions'import * as getters from'. / module/moduleA' / / Module Aimport moduleB from'. / module/moduleB' / / Module BVue.use (Vuex) export default new Vuex.Store ({actions, getters, state, mutations, modules: {moduleA, moduleB}})

ModuleA.js / moduleB.js file

/ / each module has its own state, mutation, action, getter, or even nested submodules export default {state: {text: 'moduleA'}, getters: {}, mutations: {}, actions: {}}

Then we can just call it in the component.

{{getText1}} {{getText2}} computed: {getText1 () {return this.$store.state.moduleA.text;}, / / or... mapState ({getText2: state = > state.moduleB.text;})}

It can be seen that the state inside the module is local and only belongs to the module itself, so the external must be accessed through the corresponding module name.

Fifth, the simplest project example of Vuex

Sugar mapMutations and mapGetters using Vuex Grammar

1. Store data

A.vue file

Import {mapMutations} from "vuex" / / introduce mapMutationsexport default {methods: {... mapMutations ({/ / associate changeNews with SET_NEWS in mutations changeNews: "SET_NEWS"}), submit () {/ / submit a mutation named changeNews And pass in the parameter val let val = 'test news' This.changeNews (val); / / equivalent to this.$store.commit ("changeNews", val);} 2. Get data

B.vue file

Import {mapGetters} from "vuex" / / introduce mapGetters export default {computed: {/ / use vuex to read data (read data in getters.js) / / equivalent to this.$store.getters.news (vuex syntax sugar). MapGetters (["news"])}, created () {/ / get news data console.log (this.news) in getters }} 3. Store file directory structure

Index.jsimport Vue from 'vue'import Vuex from' vuex'import state from'. / state'import mutations from'. / actions'import * as getters from'. / getters'// prints logimport createLogger from 'vuex/dist/logger'Vue.use (Vuex) const debug = process.env.NODE_ENV! =' production'export default new Vuex.Store ({actions, getters, state, mutations) on the console every time you modify the state Strict: debug, / / turn on strict mode when debug=true (performance loss) plugins: debug? [createLogger ()]: []}) state.jsconst state = {news: {}} export default state;mutations.jsconst mutations = {SET_NEWS (state, val) {state.news= val}} export default mutations;actions.js// Asynchronous processing const actions = {M_NEWS ({commit}, val) {commit ('SET_NEWS', val); / / commit mutations modify}} export default actions Getters.js// usually uses getters to fetch data (this.$store.getters.news;) export const news = state = > state.news / / directly map out 4. Use store

Referencing in main.js

Import store from'. / store' / / vuex storage file new Vue ({el:'# app', router, store, components: {App}, template:'}) this is the end of the article on "use cases of Vuex". I hope the above can be helpful to you, so that you can learn more knowledge. If you think the article is good, please share it for more people to see.

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