search
HomeWeb Front-endJS TutorialDetailed explanation of modules instances of vuex2.0

Detailed explanation of modules instances of vuex2.0

Jan 18, 2018 am 09:29 AM
Detailed explanation

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="/static/imghwm/default1.png"  data-src="./assets/logo.png"  class="lazy"   alt="Detailed explanation of modules instances of vuex2.0" >
  <h1 id="useName">{{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: > ;, when clicked, dispatch an action. So how to dispatch actions in the component?

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="/static/imghwm/default1.png"  data-src="./assets/logo.png"  class="lazy"   alt="Detailed explanation of modules instances of vuex2.0" >
  <h1 id="useName">{{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 directory


const 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="/static/imghwm/default1.png"  data-src="./assets/logo.png"  class="lazy"   alt="Detailed explanation of modules instances of vuex2.0" >
  <h1 id="useName">{{useName}}</h1>

  <!-- 增加h2 展示 localJobTitle -->
  <h2 id="localJobTitle">{{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="/static/imghwm/default1.png"  data-src="./assets/logo.png"  class="lazy"   alt="Detailed explanation of modules instances of vuex2.0" >
  <h1 id="useName">{{useName}}</h1>

  <!-- 增加h2 展示 localJobTitle -->
  <h2 id="localJobTitle">{{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(&#39;login&#39;, [&#39;alertName&#39;])
 }
}
</script>

相关推荐:

Yii2 如何在modules中添加验证码的方法详解

css modules的几种技术方案_html/css_WEB-ITnose

yaf框架中modules下的目录,配置二级域名

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!

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
JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

See all articles

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

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

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.