Vuex的基本使用

Vuex笔记

概念

vuex是一个集中式存储组件数据的仓库

安装

npm indtall vuex -S

vuex仓库环境搭建

//引入vue
import Vue form 'vue'
//1、引入vuex
import Vuex from 'vuex'
Vue.use(Vuex);
//2、定义仓库
const store = new Vuex.Store({
   state:{},//状态,会转存到store上面
   mutations:{
       fn1(state,props){}
  },//用来修改store仓库中的state的唯一正途
   actions:{
       async fn2(store,props){
           const a=await ...
           store.commit('fn1','1111');
      }
  }
})
  1. store中的state中的数据只能通过调用store的commit方法提交一个mutation来更改

  2. 异步操作必须调用store的dispatch方法来提交一个action,在action中完成异步操作再提交commit更改数据

如何读取仓库中的数据

//仓库中的数据一般都是共享数据,不建议转存,更不能直接引用,一般通过计算属性来获取仓库中的数据
computed:{
   name:{
       get(){
           return this.$store.state.userName;
      },
       set(val){
           this.$store.commit('fn1',val)
      }
  }
}

如何设置仓库的state

mutations

//引入vue
import Vue form 'vue'
//1、引入vuex
import Vuex from 'vuex'
Vue.use(Vuex);
//2、定义仓库
const store = new Vuex.Store({
   state:{},//状态,会转存到store上面
   mutations:{
       fn1(state,props){}
  },//用来修改store仓库中的state的唯一正途
   actions:{}
})

actions

//引入vue
import Vue form 'vue'
//1、引入vuex
import Vuex from 'vuex'
Vue.use(Vuex);
//2、定义仓库
const store = new Vuex.Store({
   state:{},//状态,会转存到store上面
   mutations:{
       fn1(state,props){}
  },//用来修改store仓库中的state的唯一正途
   actions:{
       async fn2(store,props){
           const a=await ...
           store.commit('fn1','1111');
      }
  }
})

  • 为了保证操作的统一性,即使是同步操作我们最好也先经过actions通过actions提交到mutations

//1.通过dispatch触发actions
this.$store.dispatch('fn2','hahaha');//第二个线束用于传值进仓库,格式为字符串或者对象
//2.在actions内部再对state进行更改

getters

  • Vuex自带的计算属性,可以对共享数据进行逻辑处理并返回

//引入vue
import Vue form 'vue'
//1、引入vuex
import Vuex from 'vuex'
Vue.use(Vuex);
//2、定义仓库
const store = new Vuex.Store({
   state:{
       firstName:'西门',
       lastName:'庆'
  },//状态,会转存到store上面
   mutations:{
       fn1(state,props){}
  },//用来修改store仓库中的state的唯一正途
   actions:{
       async fn2(store,props){
           const a=await ...
           store.commit('fn1','1111');
      }
  },//更改state数据一般先触发actions
   getters:{
       fullName(state){
           return state.firstName+state.lastName
      }
  }
})
  • 定义好getters后在任意组件都能获取此公共数据

//获取方法

computed:{
   name:{
       get(){
           this.$store.getters.fullName
      }
  }
}

辅助函数

引入

//从vuex中引入的四个函数
import {mapState,mapGetters,mapMutations,mapActions} from 'vuex';

作用

这四个函数是为了简化业务组件的开发

使用

mapState & mapGetters
//函数的返回值都是一个对象并且包含需要获取的函数
computed:{
   ...mapState(["firstName"]), //参数也可写为对象模式 ...mapState({myFirstName:'firstName'})
   ...mapGetters(["fullName"])
}
mapMutations & mapActions
methods:{
   ...mapMutations(['fn1']),
  ...mapActions(['fn2'])
}

当使用辅助函数时就可以替代this.$store....这种冗长的方法去获取store里面的东西

辅助函数的参数是字符串的时候相当于在methods/computed里面的函数名和仓库里面的函数/属性同名

当参数是对象的时候,自定义别名

posted @ 2021-01-25 08:43  新成  阅读(56)  评论(0编辑  收藏  举报