# vuex基础

111 阅读2分钟

Snipaste_2022-05-24_21-53-06.png

项目中引用Vuex

1、下载包  npm i vuex@3  (vue2用3版本的vuex,vue3用4版本的vuex)
2、配置项目的main.js
import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip=false
//引入vuex
//1、引入库
import Vuex from 'vuex'
//2、安装
vue.use(Vuex)
//3、创建仓库示例
const store = new Vuex.Store()
new Vue({
    //4、挂载new Vue实例上
    store:store//对象简写----store
    render:h=>(App)
}).$mount('#app')

state :共享状态数据-------状态在组件中引用 (strict : true)

储存状态数据
使用的方式 ----$store.state.字段名
语法:
    //3、创建仓库示例
const store = new Vuex.Store({
    strict:true,//严格执行   不经过mutaitions修改strict数据,报错,不设置----数据不会全局响应
    state:{
        name:"小红",
        age:18,
        greent:'女',
        connt:0
    }
})

mutaitions: 修改state 必须通过mutations ,只能执行通步代码

修改state
使用方式 -----$store.commit -------同步
语法
        //3、创建仓库示例
const store = new Vuex.Store({
    strict:true,//严格执行   不经过mutaitions修改strict数据,报错,不设置----数据不会全局响应
    state:{
        connt:0
    },
    mutaitions:{
    addConnt(state,data){//第一个参数是store中的stare对象----data--自己设置的参数
    state.connt+=data//传参数//每次调用加 data
}
}
})

组件:组件调用aciton

actions : 执行异步操作,数据提交给 mutations 进行修改

异步操作
使用方式: ------$store.dispatch
语法:
    actions:{
        asyncAddCount(store,payload){
            //actios 的函数不能直接修改state中的数据
            //需要调用 mutations 
            //在调用中,第一个接受的参数是当前仓库的store本身。。。用commit 
            //直接使用在组件内的方式调用------this.$store
            setTimeout(()=>{
                store.commit('mutations中的方法',payload )
            },1000))
        }
        
    }

getters 简化数据的获取-----(可以进行一些数据的加工)

简化数据的获取
$store.getters.字段名
const store = new Vuex.Store({
    strict:true,//严格执行   不经过mutaitions修改strict数据,报错,不设置----数据不会全局响应
    state:{
       name:"小黄",
        list:[1,2,3,4,5,6,7,8,9]
    },
    mutaitions:{
     .........
    }
   }),
    getters:{
        lessFive:state=>state.list.filter(item =>item>5)//返回 一个 数组中大于 5 的数
  
    }

Modules ---- 拆分为不同的模块(每个属性都是一个模块对象)

modules:{

user:{name:“小红”},

setting:{name:"小黄"}

}

在不同的模块中可以包含   state  mutations  actions  getters
空间锁  namespaced:true   
设置这个后不能用全局的mutations直接修改模块state中的数据                     
方法如下:(如果模块名为“user”)
                         ...mapmutations('user(模块名)'/['方法名'])
一般不会将getters 写到模块中
因为在模块中如果要读取state每次都要点模块名.字段名...很麻烦。。。
写在modules外部的getters有一个特性,是他的state可以得到所有的模块的数据
方法:
    getters:{
        token:state=>state.user.token,
        name:state=>state.setting.name
    }

辅助函数

mapState    ...mapstate('state对象中的变量名')
mapMutations  ...mapMutations(['mutations中的方法名(同步)'])
mapActions   ...mapActions(['actions中的方法(异步)'])
mapGetters  ...mapGetters(['getters中的数据名'])

\