vuex

80 阅读1分钟

1.state:存储应用程序中的组件状态

2.mutations:更新state中组件状态

3.actions:异步操作,通过mutations去更新state中组件状态

4.getters:类似与vue.js中的计算属性computed,当状态值发生改变是才会调用它的方法

5.modules:模块化管理,当需要管理的状态繁多时,可采用模块化管理,更易维护更易阅读。

  1. vuex辅助函数-mapState

...mapState( ['属性名a' , '属性名b'] )

这行代码相当于自动帮你生成一个对应的计算属性 属性名(){ return this.$store.state.属性名 }

  ...mapState(['user'])

  //计算属性:本质还是访问vuex中的数据
  // user(){
  // return this.$store.state.user
  // }
\

登录功能

要下载3.x的版本不然会有 Cannot read properties of undefined (reading 'dispatch')的报错

下载

npm install vuex@3.0.1 --save

新建store-index.js文件

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

let store = new Vuex.Store({
  state: {
    username: ''
  },
  mutations: {
    addUser (state, username) {
      state.username = username
    }
  },
  actions: {
    saveUserName (context, username) {
      context.commit('addUser', username)
    }
  }
})

export default store

$store.commit('mutations的名字', 参数)调用mutations

在组件中通过this.$store.dispatch('actions的名字', 参数)来调用action

登录页

在登陆方法用this.$store.dispatch('saveUserName', this.username)调用

Nav组件

 computed: {
    username: function () {
      return this.$store.state.username
    },
  },

判断权限管理

要在update阶段,因为created和mounted阶段一开始就执行完毕了

(3条消息) 【Vue】如何使用vuex解决兄弟组件传值?_风无雨的博客-CSDN博客