Vuex

Vuex : 状态管理器

官网文档 https://v3.vuex.vuejs.org/zh/

作用 : 在vue项目中管理数据 ( 集中管理数据 ) , 方便数据的通讯
原因 : 组件通讯复杂, 方便进行组件通讯
优点 : 数据的更新是响应式的

使用 :

  1. 安装 yarn add vuex@3.6.2
  2. 创建配置store  ( 在store/index.js中 )
    import Vue from 'vue'
    import Vuex from 'vuex'
    Vue.use(Vuex)
    const store = new Vuex.Store({ 配置项/核心概念 })
    export default store
  3. 挂载实例    ( main.js )
    import store from '@/store'
    new Vue({
      ... ,
      store 
    })

Vuex数据流

store/index.js 中存储修改数据

const   store = new  Vuex.Store({
    //  存储数据,任何组件都可以访问这里的数据
    state: { num:10 },

    //  mutations  唯一能修改数据的地方
    mutations:{
      //  形参1: 上面仓库的state的数据对象
      //  形参2: 可选参数,接收外部传入的数据
      changeNum(state,data) { state.num += data }
    }

    //  actions 异步修改数据
    actions:{
      //   context : 上下文对象, 里面有 commit 和 dispatch 可直接调用
      //   data : 可选参数, 接收外部传入的数据
      changeNumAsync( context , data ){ 
        //  专门处理网络请求
        context.commit('changeNum',data)
      } 
    }

    //  getters 建立快捷访问
    getters:{
      username(state){ return  state.userinfo.xx }
    }
})

state 访问数据

//  第一种
$store.state.num
//  第二种
import { mapState } from 'vuex'   // 引入辅助函数mapState
computed : { ...mapState(['num']) }  // 将state里的属性映射为当前组件的计算属性

mutations 修改数据

//  第一种
$store.commit( 'fn' , data )
//  第二种
import { mapMutations } from 'vuex'
methods:{ ...mapMutations(['changeNum']) }
// 将mutations 里的方法映射为当前组件的方法

// 不推荐直接用 $store.state.num 修改数据
// 原因: 调试器不能同步  /  严格模式会报错

actions 异步修改数据

//  第一种
$store.dispatch( 'fn' , data )
//  第二种
import { mapActions } from 'vuex'
methods: { ...mapActions( ['fn'] ) }
//  将actions里的方法映射为当前组件的方法

getters 建立快捷访问方式

//  第一种
$store.getters.xx
//  第二种
import { mapGetters } from 'vuex'
computed: { ...mapGetters(['xx']) }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值