vuex的作用:用来解决vue中不同组件之间的传值问题,大量组件传值的情况下,vuex的优势就十分明显。
Vuex核心内容
成员列表:
- state 存放状态
- getters 加工state成员给外界
- mutations state成员操作
- actions 异步操作
- modules 模块化状态管理
1.1state 用来存放属性和值,类似data的作用。
export default new Vuex.Store({
state: {
title: '李焕英',
count: 0
},
})
接收方法
1.直接在vue对象内找到该属性: <p>{{ $store.state.title }}</p>
2. 通过mapState依赖
// 引入依赖
import {mapState} from 'vuex'
//将vuex内的state引入到当前组件
computed: {
...mapState(['title']), // 直接引入
...mapState({ t: (state) => state.title }) //别名引入
},
1.2getter 将state中的成员进行操作后返回给所需组件
使用方法为:
getters:{
total(state){
return state.count+10
}
}
//默认参数为state
调用方法1:直接通过vue中的$store找到该方法并直接使用即可,getter内的方法不能传参,类似computed内的方法
<p>{{ $store.getters.total }}</p>
2.mapGetters 依赖 使用方法同mapState
1.3mutations(同步方法) 唯一一个可以修改state内属性值的属性
使用方式:
mutations:{
add(state,num){
state.count += num
}
}
//内部函数的默认参数也为state
组件内调用:
1.通过$store直接调用
created() {
this.$store.commit('add', 10) // 需要使用commit函数来调用所需函数和传参
},
2.通过mapMutations引入后调用
import {mapMutations} from 'vuex'
methods:{
...mapMutations(['add'])
}
created() {
this.add(10)
},
1.4 actions 异步操作
使用方式:
actions: {
async_Add_Num(context){
setInterval(()=>{
context.commit('Add_Num',1000000000)
},2000)
}
},
// 默认参数为context,其内部有commit方法,可以调用Mutations内的方法来改变state成员的值
调用方式:
1.dispatch调用
created() {
this.$store.dispatch('async_Add_Num') //通过dispatch方法可以调用actions内的方法
},
2.mapActions 使用方式与mapMutations类似
1.5 modules当项目庞大,状态非常多时,可以采用模块化管理模式。
const test1 = {
namespaced: true,
state: {
name: 'moduleA',
type: 'module A'
},
mutations: {
updateNameByMutation(state, appendStr){
state.name = state.name + " append Str: " + appendStr
}
},
actions: {
udpateNameByAction({commit}, appendStr) {
commit("updateNameByMutation", appendStr)
}
},
getters: {
getNameA(state){
return state.name
}
}
}
const test2 = {
// 当namespaced=true 时, vuex, 将会自动给各自module 添加访问路径名。 方便区分moduel
namespaced: true,
state:{
name: 'moduleB',
type: 'module B'
},
mutations: {
updateNameByMutation(state, appendStr){
state.name = state.name + " append Str: " + appendStr
}
},
actions: {
// 如果不使用命名空间, 那么view 指向actions 的该方法时,会执行所有与指定action名相同的函数(即:这里module A,B 中该action都会执行)
udpateNameByAction({commit}, appendStr){
commit("updateNameByMutation", appendStr)
}
},
getters: {
getNameB(state){
return state.name
}
}
}
const storeInstall = new Vuex.Store({
state: {
name: 'i am root state name'
},
modules:{
// 这里的路径名: test1, test2, 在view 中 通过 mapActions('test1', [actionName]) 使用并区分需要使用的module
test1,
test2
}
})
export default storeInstall
————————————————
该部分原文链接:https://blog.csdn.net/chenzhizhuo/article/details/96872320