search
HomeWeChat AppletMini Program DevelopmentDetailed explanation of Vuex modular (module) examples

This article mainly introduces Vuex modularity to you. The editor thinks it is quite good. Now I will share it with you and give you a reference. I hope it can help you.

1. Why modularization is needed

The examples we mentioned earlier are all performed in a state tree. When a project is relatively large, all states will be gathered together. Get a relatively large object, which becomes bloated and difficult to maintain. In order to solve this problem, Vuex allows us to divide the store into modules. Each module has its own state, mutation, action, getter, and can even nest modules downwards. Let's look at a typical modularization example

const moduleA = {
 state: {....},
 mutations: {....},
 actions: {....},
 getters: {....}
}

const moduleB = {
 state: {....},
 mutations: {....},
 actions: {....},
 getters: {....}
}

const store = new Vuex.Store({
 modules: {
 a: moduleA,
 b: moduleB
 }
})

store.state.a // moduleA的状态
store.state.b // moduleB的状态

2. The local state of the module

The mutation and getter inside the module, the first parameter (state) received is the local state object of the module, rootState

const moduleA = {
 state: { count: 0},
 mutations: {
 increment (state) {
  // state是模块的局部状态,也就是上面的state
  state.count++
 }
 },
 getters: {
 doubleCount (state, getters, rootState) {
  // 参数 state为当前局部状态,rootState为根节点状态
  return state.count * 2
 }
 },
 actions: {
 incremtnIfOddRootSum ( { state, commit, rootState } ) {
  // 参数 state为当前局部状态,rootState为根节点状态
  if ((state.cont + rootState.count) % 2 === 1) {
  commit('increment')
  }
 }
 }
}

3. Namespace (be sure to read it here, otherwise you will get tricked sometimes)

In all the above examples, the actions, mutations, and getters inside the module are registered in the global namespace. If you are in moduleA and moduleB The action, mutation, or getter (called some) with the same name is declared respectively. When you use store.commit('some'), the A and B modules will respond at the same time. So, if you want your module to be more self-contained and reusable, you can add namespaced: true to make it a namespaced module. When a module is registered, all its getters, actions, and mutations will automatically call the entire naming according to the path registered by the module. For example:

const store = new Vuex.Store({
 modules: {
 account: {
  namespaced: true,
  state: {...}, // 模块内的状态已经是嵌套的,namespaced不会有影响
  getters: {  // 每一条注释为调用方法
  isAdmin () { ... } // getters['account/isAdmin']
  },
  actions: {
  login () {...} // dispatch('account/login')
  },
  mutations: {
  login () {...} // commit('account/login')
  },
  modules: {  // 继承父模块的命名空间
  myPage : {
   state: {...},
   getters: {
   profile () {...}  // getters['account/profile']
   }
  },
  posts: { // 进一步嵌套命名空间
   namespaced: true,
   getters: {
   popular () {...} // getters['account/posts/popular']
   }
  }
  }
 }
 }
})

The getters and actions that enable the namespace will receive localized getters. dispatch and commit. You do not need to add a space name prefix in the same module when using module content, and you do not need to modify the code in the module after changing the namespaced attribute.

4. Access global content (Global Assets) in the namespace module

If you want to use global state and getter, rootState and rootGetter will be passed into the getter as the third and fourth parameters. The action will also be passed in through the attributes of the context object. If you need to distribute the action or submit the mutation in the global namespace, just pass { root: true } as the third parameter to dispatch or commit.

modules: {
 foo: {
 namespaced: true,
 getters: {
  // 在这个被命名的模块里,getters被局部化了
  // 你可以使用getter的第四个参数来调用 'rootGetters'
  someGetter (state, getters, rootSate, rootGetters) {
  getters.someOtherGetter // -> 局部的getter, ‘foo/someOtherGetter'
  rootGetters.someOtherGetter // -> 全局getter, 'someOtherGetter'
  }
 },
 actions: {
  // 在这个模块里,dispatch和commit也被局部化了
  // 他们可以接受root属性以访问跟dispatch和commit
  smoeActino ({dispatch, commit, getters, rootGetters }) {
  getters.someGetter // 'foo/someGetter'
  rootGetters.someGetter // 'someGetter'
  dispatch('someOtherAction')  // 'foo/someOtherAction'
  dispatch('someOtherAction', null, {root: true}) // => ‘someOtherAction'
  commit('someMutation') // 'foo/someMutation'
  commit('someMutation', null, { root: true }) // someMutation
  }
 }
 }
}

5. Binding function with namespace

As mentioned before, after bringing the namespace, the namespace must be written when calling, but this is more cumbersome, especially when it comes to When there are multiple levels of nesting (of course, don’t nest too much during development, you will get dizzy...)

Let’s look at the general writing method

computed: {
 ...mapState({
 a: state => state.some.nested.module.a,
 b: state => state.some.nested.module.b
 }),
 methods: {
 ...mapActions([
  'some/nested/module/foo',
  'some/nested/module/bar'
 ])
 }
}

In this case, you can The module's namespace is passed as the first argument to the above function, so that all bindings will automatically use the module as a context. Simplified writing is

computed: {
 ...mapStates('some/nested/module', {
 a: state => state.a,
 b: state => state.b
 })
},
methods: {
 ...mapActions('some/nested/module',[
 'foo',
 'bar'
 ])
}

6. Module reuse

Sometimes we may create multiple instances of a module, for example:

  • Create multiple stores, They share a module

  • Registering the same module multiple times in a store

If we use a pure object to declare the module state, then this state object will be shared through references, causing data to contaminate each other.
In fact, the data in the Vue component has the same problem, so the solution is the same. Use a function to declare the module status (supported by 2.3.0+)

const MyModule = {
 state () {
 return {
  foo: 'far'
 }
 }
}

7. Summary

The content of modularity (module) has been finished here. This time we mainly explain the reasons for the emergence of modules, how to use them, global and local namespaced module namespaces, local access to global content, and map functions with namespace bindings. Reuse of functions and modules.

Quote

https://vuex.vuejs.org Vuex official documentation

Related recommendations:

vuex2.0 Detailed explanation of modules instance

Detailed explanation of Vue + Vuex Detailed explanation of using vm.$nextTick instance

Learn simple vuex and modularization

The above is the detailed content of Detailed explanation of Vuex modular (module) examples. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment