Vue-CLI3.0 project construction process series two: vuex application in the project

In the first series, we installed and configured some plug-ins commonly used in the project, and then the application of vuex in the project

Vuex official website explains as follows

In the projects I have written so far, vuex is mainly used to store user information, login status, permissions, etc., and only the usage is introduced in this article.

Create a new store folder under the src folder -> create a new index.js file

Then introduce in the main.js file:

import store from './store'

and

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

Next we start writing store

In order to facilitate project management, create new modules under the store folder to store the status of different modules

Commonly used in the project, such as user information, is used to store login user related

Create a new user.js under modules

const user = {
    state: {
        currentUser: '',
        isLogin: false
    },
    getters: {
        currentUser: state => state.currentUser,
        isLogin: state => state.isLogin
    },
    mutations: {
        userStatus(state, user) {
            if (user) {
                state.currentUser = user
                state.isLogin = true
            } else {
                state.currentUser = null
                state.isLogin = false
            }
        }
    },
    actions: {
        setUser({commit}, user) {
            commit('userStatus', user)
        }
    }
}

export default user

Introduced in the store = "index.js file

import Vue from 'vue'
import Vuex from 'vuex'
import user from './modules/user'

Vue.use(Vuex)

const store = new Vuex.Store({
    modules: { user }
})

export default store

In this way, in the project, we can get the information about the user and the current login status at any time and modify it

How to get it:

import store from './../store'
// 然后
store.getters.currentUser

or

this.$store.getters.currentUser

Modify the current user method:

import store from './../store'
// 然后
store.dispatch('setUser', 'liona')

or

import {mapActions} from 'vuex'
然后
methods: {
         ...mapActions(['setUser'])//数组里可以放多个
         }
修改的时候就可以用
this.setUser('newName')

 

Guess you like

Origin blog.csdn.net/liona_koukou/article/details/96303558