Home > Web Front-end > JS Tutorial > body text

A detailed explanation of modular organization in Vuex

亚连
Release: 2018-06-12 13:38:11
Original
1519 people have browsed it

This article mainly introduces the detailed explanation of Vuex's advanced modular organization. Now I share it with you and give it as a reference.

Homemade vuex LOGO

The first two articles explained the basic usage of Vuex, but it is definitely unreasonable to write like this in actual projects. If There are too many components, and it is impossible to put all component data in one store.js, so Vuex needs to be organized in a modular manner. First, take a look at the project structure.

Project structure

1. First execute the following command:

vue init webpack-simple vuex-demo
cd vuex-demo
npm install
npm install vuex -S
npm run dev
Copy after login

2. Follow the above Graph structure creation file directory

Vuex modular directory

3. Write files

We Just use the examples from the previous two articles. Let’s first talk about the role of each file

Define constants in types.js, use constants to replace mutation event types

User.js Write the state, getters, actions and used in the user component mutations, and finally export them uniformly (similar to store.js in the previous example)

Write the original getters in getters.js to obtain attributes

Write the original actions in actions.js , which are the actions to be executed, such as process judgment and asynchronous requests

index.js is used to assemble actions.js, getters.js, and user.js, and then export them uniformly

1. Import the index.js file in main.js and register it

import Vue from 'vue'
import App from './App.vue'
import store from './store/index.js'
new Vue({
 store,
 el: '#app',
 render: h => h(App)
})
Copy after login

2. Define constants in types.js and export them, all capital letters by default

// 定义类型常量,默认全部大写
const INCREMENT = 'INCREMENT'
const DECREMENT = 'DECREMENT'
export default {
  INCREMENT,
  DECREMENT
}
Copy after login

Note: Placing these constants in separate files allows your code collaborators to see at a glance the mutations contained in the entire app. It's up to you whether to use constants or not - this can be helpful in large projects where multiple people are working together. But if you don't like it, you don't have to do it.

3. Write the state, getters, actions and mutations used in the user component in user.js

// 导入 types.js 文件
import types from "./../types";
const state ={
  count:5
}
// 定义 getters
var getters ={
  count(state){
    return state.count
  }
}
const actions ={
  increment({ commit, state }){
    // 此处提交的事件与下方 mutations 中的 types.INCREMENT 对应,与原来 commit('increment') 的原理相同,只是把类型名换成了常量
    commit(types.INCREMENT)
  },
  decrement({commit,state}){
    if (state.count>10) {
      // 此处提交的事件与下方 mutations 中的 types.DECREMENT 对应
      commit(types.DECREMENT)
    }
  }
}
const mutations ={
  // 此处的事件为上方 actions 中的 commit(types.INCREMENT)
  [types.INCREMENT](state){
    state.count++
  },
  // 此处的事件为上方 actions 中的 commit(types.DECREMENT)
  [types.DECREMENT](state){
    state.count--
  }
}
// 最后统一导出
export default {
  state,
  getters,
  actions,
  mutations
}
Copy after login

Note: [types.INCREMENT in the mutations above ] writing method, because types.INCREMENT is an object, it cannot be written directly as a function name. You need to use the ES2015 style calculated property naming function to use a constant as the function name before it can be used normally. The original writing method is:

const mutations ={
  increment(state){
    state.count ++;
  }
}
Copy after login

4. Write the original method of determining odd and even numbers in getters.js

// 因为数据从 user.js 中获取,所以需要引入该文件
import user from './modules/user'
const getters = {
  isEvenOrOdd(state){
    // 注意数据是从 user.js 中获取的,所以写成 user.state.count
    return user.state.count % 2 == 0 ? "偶数" : "奇数"
  }
}
// 并导出
export default getters;
Copy after login

5. Write the original asynchronous operation in actions.js

// 异步操作中需要用到 increment 方法,所以需要导入 types.js 文件
import types from './types'
const actions= {
  incrementAsync({ commit, state }) {
    // 异步操作
    var p = new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve()
      }, 3000);
    });
    p.then(() => {
      commit(types.INCREMENT);
    }).catch(() => {
      console.log('异步操作');
    })
  }
}
// 最后导出
export default actions;
Copy after login

6. Assemble actions.js, getters.js, and user.js in index.js, and then export them uniformly

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
import getters from './getters'
import actions from './actions'
import users from './modules/user'
// 导出 store 对象
export default new Vuex.Store({
  getters,
  actions,
  modules:{
    users
  }
})
Copy after login

Note: When exporting the store object , because getters and actions have default values ​​in the core concepts of vuex and can be written directly. But users is not the default, so the modules object in vuex is used for export

Core concepts

7. The Vue.app file does not make any Modification

<template>
 <p id="app">
  <button @click="increment">增加</button>
  <button @click="decrement">减少</button>
  <button @click="incrementAsync">延时增加</button>
  <p>{{count}}</p>
  <p>{{isEvenOrOdd}}</p>
 </p>
</template>
<script>
import { mapGetters, mapActions } from "vuex";
export default {
 name: &#39;app&#39;,
 data () {
  return {
   msg: &#39;Welcome to Your Vue.js App&#39;
  }
 },
 computed:mapGetters([
  &#39;count&#39;,
  &#39;isEvenOrOdd&#39;
 ]),
 methods:mapActions([
  &#39;increment&#39;,
  &#39;decrement&#39;,
  &#39;incrementAsync&#39;
 ])
}
</script>
Copy after login

Finally, the thrilling time has come, whether the thing I have spent so much effort on can run

vuex modular.gif

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

AngularJS two-way data binding principle (detailed tutorial)

Related data storage and value acquisition in WeChat applet Question

How to implement the streamlined style in Vue (detailed tutorial)

How to customize the global component in vue?

The above is the detailed content of A detailed explanation of modular organization in Vuex. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!