作用:方便做不同组件的传值
下载:vue add vuex
基本语法:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {// 声明数据
// 例如:count: 0
// 调用方法:
// $store.state.count
},
getters: {//相当于是vuex里的计算属性
// 例如: count: state => state.count
// 调用方法:
// $store.getters.计算属性名
},
mutations: {//vuex里放同步方法的地方,也是唯一可以修改state数据的地方
// 参数1:固定的state,得到的就是当前vuex对象里的state
// 参数2:只能额外接收一个参数,所以如果要传多个,可以传对象或数组
// 例如: updateXXX (state, obj) { state.count = obj.count }
// 调用方法:
// $store.commit('方法名')
},
actions: {//放异步代码方法的地方
// 参数1:固定的context,也可以简写为ctx,代表了当前store对象
//参数2: 只能额外接收一个参数,所以如果要传多个,可以传对象或数组
// 例如: updateXXX (ctx, obj) { ...异步代码 // ctx.state.count = obj.count }
// 调用方法:
// this.$store.dispatch('updateXXX', 参数2)
},
modules: {//模块化
}
})
模块化语法:
//新建文件modules 放:cart.js
// 这里放购物车有关的模块数据
export default {
//开启命名空间:没有命名空间的时候,如果要调用mutations和actions里的方法,会造成调用不明确
namespaced: true
// 在模块化的vuex里,state必须是一个函数
// 且在函数里return一个对象
state () {
return {
// 数据声明到这个对象里
cartList: []
}
},
mutations: {
setCartList (state, list) {
state.cartList = list
}
},
actions: {
// 假装发请求
reqCartList (ctx) {
setTimeout(() => {
const list = [
{ id: 1, name: '皮鞋', price: 9.9 },
{ id: 2, name: '凉鞋', price: 7699 },
{ id: 3, name: '外套', price: 2399 },
{ id: 4, name: '斜挎包', price: 17900 },
]
ctx.commit('setCartList', list)
},500)
}
},
getters: {
//计算总价
totalPrice (state) {
return state.cartList.reduce((sum, v) => sum += v.price, 0)
}
}
}
导入模块:
// 导入
import cart from './modules/cart'
export default new Vuex.Store({
// 开启严格模式
strict: true,
modules: {
// 把cart注册成子模块
cart
}
})
vuex的简化函数:
-
mapState
和mapGetters
写到computed
里 -
mapMutations
和mapActions
写到methods
里
import { mapState ,mapActions,mapActions,mapMutations} from 'vuex' export default { name: 'Left', // 使用计算属性简化 computed: { // count () { // return this.$store.state.count // }, // 你下面这句话,他相当于帮你生成了上面两句计算属性 ...mapState(['count', 'age']), // reqCartList () { // this.$store.dispatch('reqCartList') // } ...mapActions(['reqCartList', 'reqFn']) } } methods: { // reqCartList () { // this.$store.dispatch('reqCartList') // } //简写: ...mapActions(['reqCartList', 'reqFn'])//...mapActions(['方法名']) ...mapMutations(['addCount','addWithNum']),//mapMutations(['方法名']) } // 后面调用就 this.方法名() 即可,写到html不用加this
使用模块化开启命名空间的调用方法:
-
$store.state.模块名.数据名(state)
-
$store.commit('模块名/方法名')(mutations)
-
$store.dispatch('模块名/方法名')(actions)
-
$store.getters['模块名/方法名'] (getter)
简化方法调用:
mapState('模块名', { 要改的名字: '名字'})
mapMutations('模块名',{ 要改的名字: '名字'})
mapActions('模块名',{ 要改的名字: '名字'})
mapGetters('模块名',{要改的名字: '名字'})