# vuex 是什么?

全局状态管理工具

# vuex 的好处

他是有订阅者的,只要 state 中的数据发生改变就立即响应到页面

# vuex 组成

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate' // 数据持久化
Vue.use(Vuex)

export default new Vuex.Store({
state: {},
mutations: {},
actions: {},
getters: {}
modules: {},
plugins: [createPersistedState()]
})

# vuex 使用

state:this.$store.state. 变量名

mutations:this.$store.commit (‘方法名’, 传递的参数)

actions:this.$store.dispatch (‘方法名’, 传递的参数)

# vuex 辅助函数

1
import {mapState,mapMutations,mapGetters,mapActions} from 'vuex'

mapState          在 computed 中使用 使用方式:…mapState ([""])
mapGetters       在 computed 中使用 使用方式:…mapGetters ([""])
mapMutations    在 methods 中使用 使用方式:…mapMutations ([""])
mapActions        在 methods 中使用 使用方式:…mapActions ([""])

# 模块化管理数据 (modules)

index.js 中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import Vue from 'vue'
import Vuex from 'vuex'
import login from './login'
import createPersistedState from 'vuex-persistedstate'

Vue.use(Vuex)

export default new Vuex.Store({
modules: {
login
},
plugins: [createPersistedState()]
})

login.js 中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const state={
show:true
}
const mutations= {
drag(state, i) {
state.show=i;
}
}
const actions= {}
const getters= {}
export default{
state, mutations, actions, getters,
namespaced: true, //开启命名空间,在各组件总 ...mapState("test1",{name:"name"})
}

页面使用

state:this.$store.state.login.show

mutations:this.$store.commit (‘login / 方法名’, 传递的参数)

actions:this.$store.dispatch (‘login / 方法名’, 传递的参数)

更新于

请我喝[茶]~( ̄▽ ̄)~*

高祥 微信支付

微信支付

高祥 支付宝

支付宝

高祥 贝宝

贝宝