Vue state management store of Vue development example (14)

introduction

Vue is one of the most popular front-end frameworks. As a front-end developer, you should master it proficiently. If you plan to learn the development process of Vue, then come on, Brother Ming will take you to get started quickly and take you to fly!
Even if you are not a front-end developer, it is necessary to have a certain understanding of the front-end development process. No one is sure whether the company will let me do the front-end in the future. It does not take a lot of time to do some simple examples. It can improve your self-confidence and sense of accomplishment, so follow Brother Ming, there is nothing wrong, come on!

navigation

✪  Vue Development Example Directory General Index◄Previous [ 13] Installation and use of axios and mockjs►Next [ 15] Dynamic Routing

overview

When working on Vue projects, the store state manager can help us complete some data storage and management. The popular understanding is that all the variables stored in the store are global variables, and updates can be submitted through methods, and other pages and components will also be updated synchronously. Take to the latest value.

method describe
state State tree: define arrays, objects, characters that need to be managed
getters Similar to computed properties, when you need to derive some state from the state of the store, you need to use a getter. The getter will accept the state as the first parameter, and the return value of the getter will be cached according to its dependencies. Only the dependent values ​​​​in the getter Changes will be recalculated.
mutation The only way to change the state of the store is to submit a mutation. Each mutation has an event of string type and a callback function. We need to change the value of the state to change in the callback function. We want to execute this callback function, then we need to execute a corresponding calling method: store.commit
  1. Vuex's state store is reactive. When the Vue component reads the state from the store, if the state in the store changes, the corresponding component will be updated accordingly.
  2. The state in the store cannot be changed directly. The only way to change the state in the store is to explicitly commit the mutation.

Installation configuration and simple use

  1. Install vuex support

npm install vuex --save

  1. Create a store folder under src, create store.js --> introduce vue and vuex in store.js
  1. Introduce vue and vuex, and use Vue.use(Vuex) [very important]
  2. Create state and mutations
  3. export export Vuex.Store instance
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const state ={
    
    
    username: '明世隐',
}
const mutations ={
    
    
    setUser (state, name) {
    
    
        state.username = name
    },
}
export default new Vuex.Store({
    
    
    state,
    mutations
})

  1. It is configured in main.js, so that it can be imported globally, and each page to be used in the province is imported separately.
  1. import store from ‘./store/store.js’;
  2. Introduced in new Vue
import Vue from 'vue'
import App from './App.vue'
import VueRouter from "vue-router"
import ElementUI from 'element-ui';
import router from "./router";
import 'element-ui/lib/theme-chalk/index.css';
import '@/assets/css/global.css';

import axios from 'axios';
Vue.prototype.$axios =axios;

import './mock/mock.js';
import store from './store/store.js';

Vue.use(ElementUI).use(VueRouter);

Vue.config.productionTip = false

new Vue({
    
    
  router,
  store,
  render: h => h(App),
}).$mount('#app')

  1. page code

Syntax: $store.state.XXX (XXX attribute name)

<template>
    <div>
        <h1>{
    
    {
    
    $store.state.username}}</h1>
    </div>
</template>
  1. console error
Uncaught TypeError: Object(...) is not a function
    at resetStoreState (webpack-internal:///../node_modules/vuex/dist/vuex.esm-browser.js:153:70)
    at new Store (webpack-internal:///../node_modules/vuex/dist/vuex.esm-browser.js:945:3)
    at eval (webpack-internal:///./src/store/store.js:15:64)
    at Module../src/store/store.js (app.js:1478:1)
    at __webpack_require__ (app.js:854:30)
    at fn (app.js:151:20)
    at eval (webpack-internal:///./src/main.js:23:74)
    at Module../src/main.js (app.js:1442:1)
    at __webpack_require__ (app.js:854:30)
    at fn (app.js:151:20)

Reason:
Vue 2.x and Vuex 4.x versions do not correspond to
Vue 3 and Vuex 4, and Vue 2 matches Vuex 3
Solution:
Uninstall the original installed vuex4

npm uninstall vuex --save

Install vuex3

npm install vuex@3 --save

  1. page effect

insert image description here

commit changes

Use the commit method, the syntax is as follows:

this.$store.commit('commit method name', data);

  1. A state field userState and submitted method setUserState in store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const state ={
    
    
    username: '明世隐',
    userState:0
}
const mutations ={
    
    
    setUser (state, name) {
    
    
        state.username = name
    },
    setUserState (state, data) {
    
    
        state.userState +=data
    },
}
export default new Vuex.Store({
    
    
    state,
    mutations
})

  1. Add a display field and button to the page
<template>
    <div>
        <h1>{
    
    {
    
    $store.state.username}}</h1>
        数据状态:{
    
    {
    
    $store.state.userState}}
        <el-button @click="addState">状态+1</el-button>
    </div>
</template>
  1. How to update the page by adding a button
addState(){
    
    
    this.$store.commit('setUserState',1);
}
  1. page effect

insert image description here

getters use

Modify the data, such as the user status in the above example, we assume the following:
0: Invalid
1: Level 1
2: Level 2
...

  1. Add getters in store.js to modify data and export getters
const getters = {
    
    
    getUserState (state) {
    
    
        let data;
        if(state.userState==0){
    
    
            data='无效'
        }else{
    
    
            data = state.userState+'级'
        }
        return data;
    }
}
export default new Vuex.Store({
    
    
    state,
    mutations,
    getters
})
  1. Use this getters on the page
计算数据状态:{
    
    {
    
    $store.getters.getUserState}}
  1. page effect
    insert image description here

display in other pages (components)

Add display directly on the footer page

Data state: { {$store.state.userState}}

When the state in state is updated, it will be updated synchronously:
insert image description here

modulesMultiple modules

  1. Create folder module under store and create two files moduleA.js moduleB.js

moduleA.js defines the username of state as module_a_user

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
    
    
    state:{
    
    
        username:"module_a_user"
    },
    mutations:{
    
    },
    getters:{
    
    }
})

moduleB.js defines the username of state as module_b_user

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
    
    
    state:{
    
    
        username:"module_b_user"
    },
    mutations:{
    
    },
    getters:{
    
    }
})
  1. Create modules in store.js and export

Don’t forget to add the import statement
import moduleA from “./module/moduleA”;
import moduleB from “./module/moduleB”;

const modules = {
    
    
    a:moduleA,
    b:moduleB
}
export default new Vuex.Store({
    
    
    state,
    mutations,
    getters,
    modules
})
  1. The code that uses these two modules in the page

Syntax: $store.state.module name.field name

module用户a:{
    
    {
    
    $store.state.a.username}}
<br>
module用户b:{
    
    {
    
    $store.state.b.username}}
  1. page effect

insert image description here

summary

This section summarizes "Vue state management store", I hope it can be helpful to everyone, please help [Like] + [Favorite] + [Punch in the comment area] If you are interested in learning Java and front-end with Xiao Ming Yes, [follow a wave] Don't get lost.
Please go to the bottom of the article to help [One-click three links] Thank you!

insert image description here

navigation

✪  Vue Development Example Directory General Index◄Previous [ 13] Installation and use of axios and mockjs►Next [ 15] Dynamic Routing

Popular column recommendation

【1】Java mini-games (Tetris, Plants vs. Zombies, etc.)
2】JavaWeb project combat (library management, dormitory management, etc.)
【3】JavaScript wonderful examples (aircraft wars, verification codes, etc.)
200 cases
[5] Learn Java from zero, learn Java with fun
[6] IDEA from zero to proficient
insert image description here

Guess you like

Origin blog.csdn.net/dkm123456/article/details/124466583