Detailed explanation of modules instances of vuex2.0
This article mainly introduces the modules of vuex2.0. The editor thinks it is quite good. Now I will share it with you and give you a reference. Let’s follow the editor to take a look, I hope it can help everyone.
What is module?
Background: State in Vue uses a single state tree structure. All the states should be placed in the state. If the project is more complex, the state is a large object. The store object will also become very large and difficult to manage.
module: Each module can have its own state, mutation, action, and getters, making the structure very clear and easy to manage.
How to use module?
General structure
const moduleA = { state: { ... }, mutations: { ... }, actions: { ... }, getters: { ... } } const moduleB = { state: { ... }, mutations: { ... }, actions: { ... } } const store = new Vuex.Store({ modules: { a: moduleA, b: moduleB})
Data inside the module: ①Internal state, the state inside the module is local, That is, the module is private, such as the list data in the car.js module state, which we need to obtain through this.$store.state.car.list; ② Internal getters, mutations, and actions are still registered in the global namespace. This This is so that multiple modules can respond to the same mutation at the same time; the result of this.$store.state.car.carGetter is undefined, which can be obtained through this.$store.state.carGetter.
Passing parameters: getters====({state(local state),getters(global getters object),roosState(root state)}); actions====({state(local State), commit, roosState (root state)}).
Create a new project to experience it, create a new project vuemodule through vue –cli, don’t forget to install vuex.
1, in the src directory Create a new login folder and create index.js in it to store the status of the login module. For the sake of simplicity, I put all the state, actions, mutations, and getters under the module in the index.js file.
First simply add a status to it, userName: “sam”
const state = { useName: "sam" }; const mutations = { }; const actions = { }; const getters = { }; // 不要忘记把state, mutations等暴露出去。 export default { state, mutations, actions, getters }
2, in the src directory, create a new store.js This is The root store, which introduces the login module through the modules attribute.
import Vue from "vue"; import Vuex from "Vuex"; Vue.use(Vuex); // 引入login 模块 import login from "./login" export default new Vuex.Store({ // 通过modules属性引入login 模块。 modules: { login: login } })
3, introduce store in main.js and inject it into the vue root instance.
import Vue from 'vue' import App from './App.vue' // 引入store import store from "./store" new Vue({ el: '#app', store, // 注入到根实例中。 render: h => h(App) })
4. Obtain the state under login through the computed attribute in app.vue. Note here that in the absence of modules, the component passes this.$ The store.state.attribute name can be obtained, but after there are modules, the state is restricted to the login namespace (module), so the module name (namespace) must be added in front of the attribute name, and this.$store.state is passed in the component. .Module name.Attribute name, here is the status successfully obtained from this.$store.state.login.userName
<template> <p id="app"> <img src="./assets/logo.png"> <h1>{{useName}}</h1> </p> </template> <script> export default { // computed属性,从store 中获取状态state,不要忘记login命名空间。 computed: { useName: function() { return this.$store.state.login.useName } } } </script>
component. The project directory and display are as follows
4. Change the name through actions and mutations. This involves dispatch action, commit mutations, and mutations to change the state.
First Add changeName action and CHANGE_NAME mutations in the login folder index.js.
const mutations = { CHANGE_NAME (state, anotherName) { state.useName = anotherName; } }; const actions = { changeName ({commit},anotherName) { commit("CHANGE_NAME", anotherName) } };
Add a button in app.vue:
In a module, state is restricted to the module's namespace and requires a namespace to access. But actions, mutations, and actually getters are not restricted. By default, they are registered in the global namespace. The so-called registration in the global namespace actually means that the way we access them is the same as that without modules. The times are the same. For example, when there was no module, this.$store.dispatch("actions"), now that there are modules, the actions are also written under the module (changeName is written to index.js in the login directory), we can still write like this, this.$store.dispatch(“changeName”), the getters in the component are also obtained through the getters in this.$store.getters.module.
<template> <p id="app"> <img src="./assets/logo.png"> <h1>{{useName}}</h1> <!-- 添加按钮 --> <p> <button @click="changeName"> change to json</button> </p> </p> </template> <script> export default { // computed属性,从store 中获取状态state,不要忘记login命名空间。 computed: { useName: function() { return this.$store.state.login.useName } }, methods: { // 和没有modules的时候一样,同样的方式dispatch action changeName() { this.$store.dispatch("changeName", "Jason") } } }
5, local parameters
Although dispatch action and commit mutations can be used globally, the actions, mutations and getters written in the module, they obtain The default parameters are not global, they are local and limited to the module in which they are located. For example, mutations and getters will get state as the first default parameter. This state parameter is the state object limited to the module where the mutations and getters are located. The mutations and getters in the login folder will only get the state in the current index.js as parameter. Actions will get a context object as a parameter. This context object is the instance of the current module. The module is equivalent to a small store.
So how can we get the state and getters in the root store? Vuex provides rootState and rootGetters as the default parameters in getters in the module. The context object in actions will also have two more properties, context.getters and context.rootState. These global default parameters are ranked behind the local parameters.
We add state in store.js, getters:
export default new Vuex.Store({ // 通过modules属性引入login 模块。 modules: { login: login }, // 新增state, getters state: { job: "web" }, getters: { jobTitle (state){ return state.job + "developer" } } })
index.js
in the login directoryconst actions = { // actions 中的context参数对象多了 rootState 参数 changeName ({commit, rootState},anotherName) { if(rootState.job =="web") { commit("CHANGE_NAME", anotherName) } } }; const getters = { // getters 获取到 rootState, rootGetters 作为参数。 // rootState和 rootGetter参数顺序不要写反,一定是state在前,getter在后面,这是vuex的默认参数传递顺序, 可以打印出来看一下。 localJobTitle (state,getters,rootState,rootGetters) { console.log(rootState); console.log(rootGetters); return rootGetters.jobTitle + " aka " + rootState.job } };
app.vue 增加h2 展示 loacaJobTitle, 这个同时证明了getters 也是被注册到全局中的。
<template> <p id="app"> <img src="./assets/logo.png"> <h1>{{useName}}</h1> <!-- 增加h2 展示 localJobTitle --> <h2>{{localJobTitle}}</h2> <!-- 添加按钮 --> <p> <button @click="changeName"> change to json</button> </p> </p> </template> <script> import {mapActions, mapState,mapGetters} from "vuex"; export default { // computed属性,从store 中获取状态state,不要忘记login命名空间。 computed: { ...mapState({ useName: state => state.login.useName }), // mapGeter 直接获得全局注册的getters ...mapGetters(["localJobTitle"]) }, methods: { changeName() { this.$store.dispatch("changeName", "Jason") } } } </script>
6, 其实actions, mutations, getters, 也可以限定在当前模块的命名空间中。只要给我们的模块加一个namespaced 属性:
const state = { useName: "sam" }; const mutations = { CHANGE_NAME (state, anotherName) { state.useName = anotherName; } }; const actions = { changeName ({commit, rootState},anotherName) { if(rootState.job =="web") { commit("CHANGE_NAME", anotherName) } }, alertName({state}) { alert(state.useName) } }; const getters = { localJobTitle (state,getters,rootState,rootGetters) { return rootGetters.jobTitle + " aka " + rootState.job } }; // namespaced 属性,限定命名空间 export default { namespaced:true, state, mutations, actions, getters }
当所有的actions, mutations, getters 都被限定到模块的命名空间下,我们dispatch actions, commit mutations 都需要用到命名空间。如 dispacth("changeName"), 就要变成 dispatch("login/changeName"); getters.localJobTitle 就要变成 getters["login/localJobTitle"]
app.vue 如下:
<template> <p id="app"> <img src="./assets/logo.png"> <h1 @click ="alertName">{{useName}}</h1> <!-- 增加h2 展示 localJobTitle --> <h2>{{localJobTitle}}</h2> <!-- 添加按钮 --> <p> <button @click="changeName"> change to json</button> </p> </p> </template> <script> import {mapActions, mapState,mapGetters} from "vuex"; export default { // computed属性,从store 中获取状态state,不要忘记login命名空间。 computed: { ...mapState("login",{ useName: state => state.useName }), localJobTitle() { return this.$store.getters["login/localJobTitle"] } }, methods: { changeName() { this.$store.dispatch("login/changeName", "Jason") }, alertName() { this.$store.dispatch("login/alertName") } } } </script>
有了命名空间之后,mapState, mapGetters, mapActions 函数也都有了一个参数,用于限定命名空间,每二个参数对象或数组中的属性,都映射到了当前命名空间中。
<script> import {mapActions, mapState,mapGetters} from "vuex"; export default { computed: { // 对象中的state 和数组中的localJobTitle 都是和login中的参数一一对应。 ...mapState("login",{ useName: state => state.useName }), ...mapGetters("login", ["localJobTitle"]) }, methods: { changeName() { this.$store.dispatch("login/changeName", "Jason") }, ...mapActions('login', ['alertName']) } } </script>
相关推荐:
css modules的几种技术方案_html/css_WEB-ITnose
The above is the detailed content of Detailed explanation of modules instances of vuex2.0. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Detailed explanation of the mode function in C++ In statistics, the mode refers to the value that appears most frequently in a set of data. In C++ language, we can find the mode in any set of data by writing a mode function. The mode function can be implemented in many different ways, two of the commonly used methods will be introduced in detail below. The first method is to use a hash table to count the number of occurrences of each number. First, we need to define a hash table with each number as the key and the number of occurrences as the value. Then, for a given data set, we run

Windows operating system is one of the most popular operating systems in the world, and its new version Win11 has attracted much attention. In the Win11 system, obtaining administrator rights is an important operation. Administrator rights allow users to perform more operations and settings on the system. This article will introduce in detail how to obtain administrator permissions in Win11 system and how to effectively manage permissions. In the Win11 system, administrator rights are divided into two types: local administrator and domain administrator. A local administrator has full administrative rights to the local computer

Detailed explanation of division operation in OracleSQL In OracleSQL, division operation is a common and important mathematical operation, used to calculate the result of dividing two numbers. Division is often used in database queries, so understanding the division operation and its usage in OracleSQL is one of the essential skills for database developers. This article will discuss the relevant knowledge of division operations in OracleSQL in detail and provide specific code examples for readers' reference. 1. Division operation in OracleSQL

Detailed explanation of the remainder function in C++ In C++, the remainder operator (%) is used to calculate the remainder of the division of two numbers. It is a binary operator whose operands can be any integer type (including char, short, int, long, etc.) or a floating-point number type (such as float, double). The remainder operator returns a result with the same sign as the dividend. For example, for the remainder operation of integers, we can use the following code to implement: inta=10;intb=3;

Detailed explanation of the usage of Vue.nextTick function and its application in asynchronous updates. In Vue development, we often encounter situations where data needs to be updated asynchronously. For example, data needs to be updated immediately after modifying the DOM or related operations need to be performed immediately after the data is updated. The .nextTick function provided by Vue emerged to solve this type of problem. This article will introduce the usage of the Vue.nextTick function in detail, and combine it with code examples to illustrate its application in asynchronous updates. 1. Vue.nex

PHP-FPM is a commonly used PHP process manager used to provide better PHP performance and stability. However, in a high-load environment, the default configuration of PHP-FPM may not meet the needs, so we need to tune it. This article will introduce the tuning method of PHP-FPM in detail and give some code examples. 1. Increase the number of processes. By default, PHP-FPM only starts a small number of processes to handle requests. In a high-load environment, we can improve the concurrency of PHP-FPM by increasing the number of processes

The modulo operator (%) in PHP is used to obtain the remainder of the division of two numbers. In this article, we will discuss the role and usage of the modulo operator in detail, and provide specific code examples to help readers better understand. 1. The role of the modulo operator In mathematics, when we divide an integer by another integer, we get a quotient and a remainder. For example, when we divide 10 by 3, the quotient is 3 and the remainder is 1. The modulo operator is used to obtain this remainder. 2. Usage of the modulo operator In PHP, use the % symbol to represent the modulus

Detailed explanation of Linux system call system() function System call is a very important part of the Linux operating system. It provides a way to interact with the system kernel. Among them, the system() function is one of the commonly used system call functions. This article will introduce the use of the system() function in detail and provide corresponding code examples. Basic Concepts of System Calls System calls are a way for user programs to interact with the operating system kernel. User programs request the operating system by calling system call functions
