Vuex study notes (you can see it at a glance)

Introducing vux

vuex: It is a state manager specially developed for vue.js. It uses centralized storage of all component states. Through vuex, we can solve the problem of data sharing between components, and it is also convenient for us to manage and maintain later.

The composition of vuex

1.state: store state, such as the data you want to store
2.getters: computed attributes, you can get the data stored in the state through this. store . getters 3. mutations: change the state, the only state that can change the state is through Submit mutations to change, this. store.getters to get the data stored in the state 3. mutations: change the state, the only state that can change the state is to change by submitting mutations, this.s t ore . get t ers to obtain the data stored in s t a t e 3. m u t a t i o ns : change the state, the only way to change the state of s t a t e is by submitting m u t a t i o n s to change, t hi s . store.commit()
4.actions: asynchronous operation, asynchronous mutations, can be distributed through dispatch to change the state
5.modules: modular management store (warehouse), Each module has its own state, mutation, action, getter

Use of vuex

1. Install the vuex dependency package
npm install vuex@next --save
//官网 https://vuex.vuejs.org/zh/
2. Create a stoar folder and put index.js in it
// 导入vuex 创建实例方法
import {
    
     createStore } from 'vuex'
// 创建实例对象
const store = createStore({
    
    
state() {
    
    
return {
    
    
// 共用属性:用户信息
userInfo: {
    
    }
}
},
mutations: {
    
    
// 共用方法: 设置用户信息
setUserInfo(state, user) {
    
    
state.userInfo = user
}
}
})
// 导出数据对象
export default store
3. Globally refer to the vuex file (in main.js)
//导入文件
import store from './store'
//挂载使用
app.use(store)
4. Use on the page (what I wrote here is Login.vue to pass values ​​to the user page)

Login.vue page

//引入useStore函数
import {
    
     useStore } from "vuex";
//声明useStore方法
const store = useStore();
// 登录成功后获取用户信息
getUserInfo().then((res2) => {
    
    
// console.log(res2);
//将登录成功后获取用户信息存入到store共用方法的setUserInfo方法中
store.commit("setUserInfo", res2);
});

Get directly from the user page

<template>
<!-- 使用store属性中userInfo数据 -->
<div>{
    
    {
    
     $store.state.userInfo }}</div>
</template>

Guess you like

Origin blog.csdn.net/z2000ky/article/details/128687936