一、Vuex的概述
1.什么是Vuex?
1. vuex是为Vue.js应用程序开发的状态管理模式。采用集中式储存管理应用所有组件的状态,并以相应的规则保证状态已可预测的方式发生变化。
2. 能够在Vuex集中管理共享的数据,便于开发和后期进行维护。
3. 能够高效的实现组件之间的数据共享,提高开发效率。
4. 储存在vuex中的数据是响应式的,当数据发生改变时,页面中的数据也会同步更新。
2.Vuex的基本使用
- 安装
npm install vuex --save
- 创建store.js文件
import Vue fron 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
//按需导出
export const store = new Vuex.store({
state:{
//数据
},
//只有mutations中定义的函数,才有权力修改state的数据
mutations:{
//方法
},
actions:{
methodAsync(context) {
// 异步操作
},
},
getters:{
//数据加工
}
})
- 将stroe.js挂载到Vue实例 main.js文件
//按需引入
import { store } from './store/store'
new Vue({
store,
router,
render: h => h(App),
}).$mount('#app')
二、Vuex的核心
1. state
- state是什么?
State 提供唯一的公共数据源,所有共享的数据都要统一放到 Store 中的 State 中存储
- 获取state中的数据的方式
//在store.js声明state
state:{
//数据
}
/**
方式一
*/
//1.在对应的vue组件中
this.$store.state 全局数据名称
/**
方式二
*/
// 1.在对应 vue 组件中导入 mapState
import { mapState } from 'vuex'
// 2. 然后数据映射为计算属性
computed:{
// products(){
// // return this.$store.state.products;
// },
...mapState([
"products"
]),
},
2. Mutation
- Mutation是什么
Vuex 不支持直接修改 state 中的数据,需要 Mutation 修改间接 state 中的数据
- Mutation的使用方式
//1.先在store.js中声明
mutations:{
// 参数 1:永远都是 state 也就是 $state 对象
// 参数 2:调用方法传递的参数,可以没有
method(state,step){
// 操作
}
}
/**
方式一
*/
//在对应的vue组件中使用commit函数调用mutations中对应函数
this.$store.commit('Mutation函数名','参数')
/**
方式二
*/
//1. 在对应的vue组件中导入mapMutations
import { mapMutations } from 'vuex'
//2.将Mutation 函数映射成methods函数
methods:{
...mapMutations(['method'])
}
3. Action
- Action是什么?
在 Mutations 中不能编写异步的代码,会导致 vue 报错,vuex 中提供了 Action 来执行异步操作。
- Action 的使用方式
// 在store.js中声明异步函数
actions:{
mthodAsync(context,'参数'){
//异步操作
}
/**
方式一
*/
// 1.在对应的vue组件中
this.$store.dispatch('异步函数名','参数')
/**
方式二
*/
// 1. 在组件中引入mapActions
import { mapActions } from 'vuex'
// 2. 将 action 函数映射为 methods 函数
methods:{
// reducePrice(amount){
// return this.$store.state.products.forEach(product => {
// product.price -= 1
// })
// this.$store.commit('reducePrice')
// this.$store.dispatch('reducePrice',amount)
// }
...mapActions([
"异步函数名"
])
}
4. Getter
- Getter是什么?
Getter是用于对store中数据进行加工处理形成新的数据,他只会包装Store中保存的数据,并不会修改 Store 中保存的数据。 当 Store 中的数据发生变化时,Getter 生成的内容也会随之变化
- Getter 的使用方式
// 在 store.js 中添加 getter 属性
getters:{
//添加了一个属性
属性名 : state => {
return "修饰后的内容";
}
}
/*
方式一
*/
// 在对应 vue 组件中使用以下方式
this.$store.getters.属性名
/*
方式二
*/
// 1. 在对应 vue 组件中引入 mapGetter
import { mapGetters } from 'vuex'
// 2. 将 Getter 属性映射为 计算属性
computed:{
...mapGetters(['showNum'])
}