状态管理中心—Vuex的用法(仓库)
为什么每次都要在mutation里改变数据?
因为只有这个我们才能在vue的开发工具Devtools里面观察到是那个组件改变了数据。
- State(操作数据)
- Mutations(同步操作改变数据)
- Actions(异步/同步操作改变数据)
//stores.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state://存放一些变量
{
count:0,
},
mutations://存放一些同步改变数据的操作(方法)
//都会自动传入一个参数state,这个参数可以用于改变state中变量的值
{
add(state){
state.count++;
},
decrease(state){
state.count--;
}
},
actions://异步操作:这里传入的是context上下文
//在mutations里定义一个方法以后通过commit进行触发
{
delayAdd(context){
setTimeout(() => {
context.commit('add')
},1000)
}
}
})
- 在组件中使用vuex里面的值:
- 1.在computed里面定义一个变量去接收值。
computed:{
count(){
return this.$store.state.count
}
}
- 2.mapState辅助函数(返回的是一个对象):当一个组件需要获取多个状态时,如果都声明为计算属性会有些重复,可以使用辅助函数。(相对于把vuex里面的数据映射出去,映射到计算属性里。)
import {mapState} from 'vuex'
computed: mapState({
//方法一:传字符串(字符串参数等同于state => state.count)
count:'count'
//方法二:使用箭头函数
count: state => state.count
})
- 3.将mapState和其他的计算属性合并,可以将mapState展开
import {mapState} from 'vuex'
computed: {
//这里可以写其他的计算属性
...mapState({
//方法一:传字符串(字符串参数等同于state => state.count)
count:'count'
//方法二:使用箭头函数
count: state => state.count
})
}
- 如何改变state的值:只能通过提交mutations,而提交mutations只能通过commit这个操作。
- mutations触发的方式:
<button @click='add'>增加</button>
methods:{
add(){
//都是通过commit提交的
this.$store.commit('add');
}
}
- actions触发的方式:(通过dispatch操作)
methods:{
add(){
//都是通过commit提交的
this.$store.dispatch('delayAdd');
}
}
状态管理中心—vuex的高级用法
- vuex中的计算属性—Getters
getters里面的每一个函数都接收一个参数:state
//在store.js里面(在vuex里进行定义)
getters:{
doubleCount(state){
return state.count * 2
}
}
2.在相应的组件中进行使用
import {mapState} from 'vuex'
computed: {
...mapState({
//方法一:传字符串(字符串参数等同于state => state.count)
count:'count'
//方法二:使用箭头函数
count: state => state.count
}),
//这里可以写其他的计算属性
doubleCount(){
return this.$store.getters.doubleCount
}
}
3.mapGetters辅助函数
import {mapState, mapGetters} from 'vuex'
computed: {
...mapState({
//方法一:传字符串(字符串参数等同于state => state.count)
count:'count'
//方法二:使用箭头函数
count: state => state.count
}),
//1.名字和store.js中定义的一致时,可以直接传一个字符串映射过去,直接使用数组形式
...mapGetters([
'doubleCount'
])
//...mapGetters({
//2.想要去不同的名字的时候则需要使用对象形式
// doubleTodoCount:'doubleCount'
// })
//这里可以写其他的计算属性
}
- 模块化概念—Modules
- 首先建立store文件夹,里面有一个入口文件为index.js,还有其他模块的js文件(此处以text.js为例)。
- 在index.js文件里面导入其他模块:
//index.js
import Vue from 'vue'
import Vuex from 'vuex'
import text from './text'
Vue.use(Vuex)
export default new Vuex({
moudles:{
text
}
})
- 在text.js文件里放置相应的其他内容
//text.js
export default({
state:{
count:0
},
getters:{
doubleCount(state){
return state.count * 2
}
},
mutations:{
add(state){
state.count++;
},
decrease(state){
state.count--;
}
},
actions:{
delayAdd(context):{
setTimeout(() => {
context.commit('add');
},1000)
}
}
})
- 在组件中使用时则需要添加上模块的名字:
import {mapState} from 'vuex'
computed: mapState({
//使用箭头函数
count: state => state.text.count
})