Vuex笔记

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式

vuex的核心是store(仓库)

store创建index.js

main引入'@/store'变成全局仓库

vue调用store

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({    // export default输出
// state相当于组件中的data,专门用来存放全局的数据
state:{
num:0
},
// getters相当于组件中的computed,getters是全局的,computed实时组件内
getters:{
getNum(state) {
return state.num
}
},
// 相当于组件的methods,不能使用异步方法(定时器/axios)
// 更改vuex的store中的状态的唯一方法是提交mutations
mutations:{
// 传参命名payload(形参),如果组件在commit时,有传这个参数过来,就存在,如果没有就是undefined
increase(state,payload){
state.num +=payload ? payload : 1;
},
decrease(state){
state.num--;
}
// 处理异步,实际修改状态值,依然是mutations
actions:{
decreaseAsync(context){
context.commit('decrease')
}
},
modules:{}
})

组件中使用方法

$store.state.num

$store.getters.getNum

组件方法中使用

this.$store.state.num

this.$store.commit('increase',2)

this.$store.disptch('decrease')

image.png

 

image.png

辅助函数:mapState和mapGetters在组件中都是写在computed里面

import {mapState} from 'vuex'
import {mapGetters}from 'vuex'
import {mapMutations,mapActions}from 'vuex'
export default{
computed:{
...mapState(['num'])
...mapGetters(['getNum'])
},
methods:{
...mapMutations(['increase']),
...mapAction(['decreaseAsync'])
}
}

 

image.png

 

拆分写法:store中所有属性,都可以拆分成单独的js文件来书写

将state,getters,mutations,actions分开为js文件,

export default {
getNum(state) {
return state.num
}
}

index.js

在store文件夹创建users文件夹,创建5个js文件,引入modules

users文件夹index.js

import state from './state'
import getters from './getters'
import mutations from './mutation'
import actions from './actions'
export default {
namespaced:true,
state,
getters,
mutations,
actions,
modules:{}
}
import state from './state'
import user from './users/index'
export default new Vuex.Store({
state,
getters,
mutations,
actions,
modules:{
users,
}
})

image.png

 子文件夹中index.js要有命名空间namespaced

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值