Vuex使用
什么时候需要使用vuex?
1.当项目使用了vue-router,并且多个页面之间需要共享数据的时候。
2.共享数据难以统一管理的时候。
1.安装vuex
2.在src目录下创建一个
store/index.js 文件,配置仓库的数据
思考项目中哪些数据要放在仓库
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| import Vue from 'vue';
import Vuex from "vuex"
Vue.use(Vuex);
const state = { name:"泰勒斯威夫特" } const getters = {
}
const store = new Vuex.Store({ state:state, getters });
export default store;
|
3.在Vue 实例中配置
在 main.js 中,即 new Vue 的时候配置 store 这个选项,选项的值就是
store 的实例对象
1 2 3 4 5
| new Vue({ store:store, router, render: h => h(App), }).$mount('#app')
|
4.在组件中使用仓库的数据
####4.1使用 mapState() 这个辅助函数
1 2 3 4 5
| <template> <div> <h1>仓库中 name 为:{{ name }}</h1> </div> </template>
|
1 2 3 4 5
| import { mapState } from 'vuex' export default { computed: mapState(["name"]) }
|
4.2使用
mapState
辅助函数时,如果组件需要定义自己的计算属性,可以使用...运算符
1 2 3 4 5 6 7 8 9
| export default { computed: { ...mapState(["name"]), list01: function(){ return ["sd","df"] } } }
|
5.修改仓库中的数据
1.首先在仓库的 mutations 部分定义一个修改 state 数据的方法
1 2 3 4 5 6
| const mutations = { setName(state,payload){ state.name = payload.newName } }
|
2.组件中在methods中使用 mapMutations 这个辅助函数
1 2 3
| methods:{ ...mapMutations(["setName"]) }
|
上述写法展开为:
1 2 3 4 5 6
| methods:{ setName(payload){ this.$store.commit('setName',payload); } }
|
### 6.获取仓库中 getters 的数据 使用
mapGetters 这个辅助函数即可。
7.异步地修改仓库中的
state 数据,如 ajax、setTimeout
7.1在组件中,异步完成之后,再
commit mutations
7.2使用actions
8.modules选项
将仓库中 state 的数据,按照某种格式来做拆分,拆分成一个个小的module
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| const moduleA = { state: { ... }, mutations: { ... }, actions: { ... }, getters: { ... } }
const moduleB = { state: { ... }, mutations: { ... }, actions: { ... } }
const store = new Vuex.Store({ modules: { a: moduleA, b: moduleB } })
store.state.a store.state.b
|
#### 8.1子模块
子模块写法:暴露一个对象(包含state、mutations、getters、actions、modules等),可以继续嵌套子模块。子模块建议设置命名空间,否则子模块除
state 外其他全部会挂载到全局命名空间下。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| export default{ namespaced: true, state:{ carts:[] }, getters:{}, mutations:{ add(){ } }, actions:{} }
|
8.2在主模块配置子模块
1 2 3 4 5 6 7 8 9 10 11
| import Vue from "vue" import Vuex from "vuex"
import cart from "./modules/cart" Vue.use(Vuex)
export default new Vuex.Store({ modules:{ cart } })
|
8.3在组件中调用
1 2 3 4 5 6 7 8 9 10 11
| import { mapMutations } from 'vuex' export default { computed:{}, methods:{ fn1(){ this.$store.commit("cart/adds") } } }
|