Vue状态管理器state(Vuex)

一、什么是Vuex

  1. Vuex是一个专为Vue.js应用程序开发的状态管理模式
  2. 采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化

二、什么是状态管理模式

  1. 状态自管理应用包含以下几个部分
    - state,驱动应用的数据源
    - view,以声明方式将 state 映射到视图
    - actions,响应在 view 上的用户输入导致的状态变化
  2. 什么时候使用
    - 多个视图依赖同一个状态
    - 来自不同视图的行为需要变更同一个状态
  3. 分模块,每个模块内需要包含
    - state:初始化的数据
    - actions:执行的异步操作
    - mutations:唯一改变数据的方式
    - namespaced:命名空间

三、分模块创建状态管理器

子模块user.js结构

// 初始化的数据
const state = {
  loginState: localStorage.getItem('isLogin') || '',
  userId: localStorage.getItem('userId') || '',
  token: localStorage.getItem('token') || ''
}

// 执行的异步操作
const actions = {}

// 唯一改变数据的方式
const mutations = {
  change_loginState (state, payload) {
    state.loginState = payload
  },
  change_userId (state, payload) {
    state.userId = payload
  },
  change_token (state, payload) {
    state.token = payload
  }
}

export default {
  namespaced: true, // 改变mutations,可以直接使用user/change_loginState
  state,
  actions,
  mutations
}

主模块引用user.js子模块

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

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
  },
  mutations: {
  },
  actions: {
  },
  modules: {
  //在modules下进行引入
    user
  }
})

四、组件中使用Vuex

  1. 登录页面,登录成功之后改变Vuex的状态
    - 组件内提交mutations,使用this.$store.commit()
// 登录成功之后,修改状态管理器的状态
this.$store.commit('user/change_loginState', 'ok')
this.$store.commit('user/change_token', res.data.token)
this.$store.commit('user/change_userId', res.data.id)
  1. 使用状态管理器中的状态,读取
// 状态管理器.状态.模块.属性
this.$store.state.user.loginState === 'ok'

this.$store.state.user.userId

五、mapState辅助函数的使用

  1. 主要用来获取状态,需要配合计算属性实现
    - 组件中提前引入Vuex的辅助函数import { mapState } from 'vuex'
// 固定写法,利用解构赋值,获取state中的loginState,userId
computed: {
        ...mapState({
            loginState: state => state.user.loginState,
            userId: state => state.user.userId
        })
    }
  1. 可以直接使用this.loginStatethis.userId找到对应状态

组件的导航守卫中无法使用this找到实例

六、mapMutations辅助函数的使用

  1. 组件中提交mutations的简化写法,需要配合methods实现
    - 组件中提前引入Vuex的辅助函数import { mapMutations } from 'vuex'
methods: {
        ...mapMutations({
            change_loginState: 'user/change_loginState',
            change_userId: 'user/change_userId',
            change_token: 'user/change_token'
        })
    }
  1. 可以替换掉commit系列方法
// this.$store.commit('user/change_loginState', 'ok')
// this.$store.commit('user/change_token', res.data.token)
// this.$store.commit('user/change_userId', res.data.id)

this.change_loginState('ok')
this.change_token(res.data.token)
this.change_userId(res.data.id)
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值