Vue state management variable modification in Vuex

Some similar to user id, user object userinfo can be defined in vuex, the user can log in or log out to call the method in mutations to make changes, the method in mutations cannot be asynchronous, if there is an asynchronous network request in a certain page, You can call the method in mutations after getting a certain result, which is equivalent to synchronization

import { createStore } from 'vuex'

export default createStore({
  state: {
    id:"",//用户登录后的id
    userinfo:{name:'',phone:""},//用户对象
  },
  getters: {
  },
  mutations: {
    //修改用户id的值
    changeuserid(state,idvalue){
      state.id=idvalue
    },
    //修改用户userinfo对象
    changeuserinfo(state,userinfovalue){
      state.userinfo=userinfovalue
    }
  },
  actions: {
  },
  modules: {
  }
})

 Read or modify state values ​​elsewhere, for example, read and modify these two states in the App.vue component:

 

mounted(){
    // console.log("App.vue组件读取main.js的全局变量globalbaseurl:",this.globalbaseurl)
    console.log("App.vue.组件内Vuex状态更改测试")
    console.log("store里面读取状态id",this.$store.state.id)
    console.log("store里面读取状态userinfo",this.$store.state.userinfo)
    console.log("store里面读取状态userinfo.name",this.$store.state.userinfo.name)
    console.log("store里面读取状态userinfo.phone",this.$store.state.userinfo.phone)

    let newinfo={name:'李四',phone:"18810452222"}//新定义的用户对象
    this.$store.commit("changeuserid",202)
    this.$store.commit("changeuserinfo",newinfo)

    console.log("更改之后读取的值----------")
    console.log("store里面读取状态id",this.$store.state.id)
    console.log("store里面读取状态userinfo",this.$store.state.userinfo)
    console.log("store里面读取状态userinfo.name",this.$store.state.userinfo.name)
    console.log("store里面读取状态userinfo.phone",this.$store.state.userinfo.phone)

  }

Guess you like

Origin blog.csdn.net/spring_007_999/article/details/130025483