一、 Vuex
1、 Vuex是什么
Vuex是实现组件全局状态管理的一种机制,可以方便的实现组件之间的数据的共享。
2、 使用Vuex统一管理状态的好处
能够在vuex中集中管理共享的数据,易于开发和后期维护
能够高效的实现组件之间的数据共享,提高开发效率
存储在vuex中的数据都是响应式的,能够实时保持数据与页面的同步
3、 Vuex 五个属性的使用
3.1 、state
¬ 提供唯一的公共数据源,所有共享的数据都要统一放到State中进行存储。
const store = new Vuex.Store({
//定义数据
state: { count : 0 }
})
¬组件访问 state 中数据的第一种方式:
this.$store.state.count
注意:在template中 {{ $store.state.数据变量 }}
组件访问 state 中数据的第二种方式:
// 1. 从vuex 中按需导入 mapState 函数
import { mapState } from ‘ vuex ‘
通过导入的mapState函数,将当前组件需要的全局数据,映射为当前组件的 computed计算属性:
// 2.将全局数据,映射为当前组件的计算属性
computed: {
…mapState { [ ‘count’ ] }
}
注意:此时在template中 不再需要$store.state访问数据,{{ count }}
3.2 、Mutation
mutation 用于修改 stare 中的数据
只能通过mutation 变更 state 中的数据,不可以直接操作 state 中的数据。
通过这种方式操作起来虽然繁琐一些,但是可以集中监控所有数据的变化
------------------ date 指携带参数 -------------------
const store = new Vuex.Store({
state: { count : 0 },
//定义mutations
mutations : {
// 第一个参数state 代表自身全局的数据对象 state,
// 第二个参数date 代表组件传递的数据
add ( state , date ) {
//变更状态
state.count ++
}
}
})
在组件中触发mutations 中函数的第一种方式
methods : {
handled ( ) {
this . $store . commit ( ‘ add ‘ , date)
}
}
在组件中出发mutation 中函数的第二种方式
// 1 . 从vuex中按需导入 mapMutations 函数
import { mapState , mapMutations } from ‘ vuex ‘
通过刚才导入的mapMutations函数,将需要的mutations函数,映射为当前组件的methods 方法
// 2 . 将指定的 mutations 函数,映射为当前组件的 methods 方法
methods : {
…mapMutations{ [ ‘ add ‘ ] }
//通过组件定义的事件去调用mapMutations 中的事件( 组件也可以直接使用add事件作为组件的事件,因为…mapMutations已经成为了methods中的方法 )
click () {
this . add ( date )
}
}
注意:不要在mutations 中执行异步操作,它是同步的
3.3 Action
Action 用于处理异步任务
如果通过异步任务本更数据,必须通过Action,而不能使用Mutation,但是在Action中还是要通过触发Mutation的方式间接变更数据。
//定义Action
const store = new Vuex.Store({
state: { count : 0 },
//定义mutations
mutations : {
// 第一个参数state 代表自身全局的数据对象 state,
// 第二个参数date 代表组件传递的数据
add ( state , date ) {
//变更状态
state.count ++
}
},
actions : {
addAsync ( context , date) {
setTimeout ( ()=> {
context.commit ( ‘ add ‘ , date)
} )
}
}
})
在组件中如何触发action 的第一种方法
methods : {
click () {
//这里的dispatch 专门触发某个action方法
this . $store . dispatch ( ‘ addAsync’ , date )
}
} //异步
在组件中如何触发action的第二种方法
// 1 . 从vuex中按需导入 mapActions 函数
import { mapActions } form ‘ vuex ‘
通过刚才导入的 mapActions 函数,将需要的actios函数,映射为当前组件methods方法:
// 2 . 将指定的actions 函数,映射为当前methods函数
methods : {
…mapActions{ [ ‘ add ‘ ] }
//通过组件定义的事件去调用mapMutations 中的事件
click () {
this . add ( date )
}
}
3.4 Getter
Getter用于对store中的数据进行加工处理形成新的数据。
Getter可以对store中已有的数据加工处理之后形成新的数据,类似vue的计算属性
Store中数据发生变化,getter的数据也会发生变化。
定义getter
const store = new Vuex.Store({
//定义数据
state: { count : 0 },
getters : {
showNum(state) {
return “ 当前最新的数据是 【‘ + state.count + ’】“
}
}
})
组件中使用getter的第一种方式
this . $store .getters.showNum
组件中使用getter的第二种方式
Import { mapGetters } from ‘ vuex ‘
Computed : {
…mapGetters( [ ‘showNum’ ] )
}
template 模板中直接使用计算属性showNum 即可