Vue状态管理

一、vuex是什么
  • vuex是vue的一个库(插件)
  • 作用:对vue应用中的多个组件的共享状态进行集中式的管理(读/写)
二、使用(单向数据流)
  • state

    • vuex中的数据源,我们需要保存的数据都存储在这里,在页面中可以通过this.$store.state来获取
    • 状态对象是唯一的
    // state
    const state = {
        uid: undefined, // 用户Id 
        nickname: undefined, // 用户昵称
    }
    
    // 使用
    this.$store.state.uid
    this.$store.state.nickname
    
  • getters

    • Getters相当于vue中的computed计算属性,getters的返回值会被缓存,只有当他所依赖的值发生改变,getters值才会重新计算。
    • 作用: Getters可以用来监听state中的值的变化
       const getters = {
           isEnable: state => state.app.isEnable,
           uid: state => state.user.uid, // 用户Id 
           nickname: state => state.user.nickname, // 用户昵称
       }
    
  • mutations (不推荐使用)

    • 修改state中数据的唯一方法(函数)
       // mutations
       const mutations = {
           SET_UID: (state, uid) => {
                 // state是上面定义的state对象
                 // uid可选参数
                state.uid = uid;
            },
            SET_NICKNAME: (state, nickname) => {
                state.nickname = nickname;
            }
       }
       
       // 调用
       this.$store.commit('updateUid', uid)
        ```
    
    
  • actions (推荐)

    • 更新状态的方法(在actions中通过提交mutations完成 – dispatch)
      const actions = {
            setUID({
                commit
            }, uid) {
                commit('SET_UID', uid);
            },
            setNickname({
                commit
            }, nickname) {
                commit('SET_NICKNAME', nickname);
            }
      }
    
作用

多组件间的数据共享(共享状态)

使用

vuex的核心管理对象模块:store

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

Vue.use(Vuex)
 
 export default new Vuex.Store({
        state, // 状态对象
        mutations, // 包含多个更新state函数的对象
        actions, // 包含多个对应事件回调函数的对象
        getters  // 包含多个getter计算属性函数的对象
 })
状态管理创建了之后需要全局映射使用
// main.js

import store from './store'

new Vue({
    el:'#app',
    components:{App},
    template:'<APP/>',
    store  // 所有组件对象都多了一个属性:$store
})

store对象

  • 所有用vuex管理的组件中都多了一个属性$store,它就是一个store对象
  • 属性 : state–>注册的state对象
    getters --> 注册的getters对象
  • 方法:this.$store.dispatch(actionsName,data) 分发调用actions
store应用
import {mapState, mapGetters,mapActions} from 'Vuex'

computed:{
      ...mapState(['xxx','xxx'])    
      //mapState的返回值:                
      {
           count(){
               return  this.$store.state['count']
           }
       }
      ...maoGetters(['xxx'])    //mapGetters的返回值:
      {xxx(){return this.$store.getters['xxx']}} 
}

methods:{
     ...mapActions(['xxxx']) 
}

vuex原理图
vuex原理图

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Joseph365

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值