状态管理就是多个组件之间的共有数据的存放。
第一种情况就是整个spa中有一套共有数据,那么就按照常规的vuex 方式进行保存就好了。
- 在src 目录下新建 store.js
const state = { count: 1 }; const mutations = { increment(state) { state.count++ }, decrement(state) { state.count-- }, }; const actions = { // increment 是vue 页面中的mapactions中的数组中对应的名字 increment: ({ commit }) => { commit('increment') // increment 对应的是 mutations 中的 increment }, decrement: ({ commit }) => { // 同理 commit('decrement') // 同理 }} // 导出 export default new Vuex.Store({ state, mutations, actions})
2 子页面 引入
<template>
<div>
vuex的文件页面count的值******{{$store.state.count}}
<div @click="increment">增加</div>
<div @click="decrement">删减</div>
</div>
</template>
<script>
import { mapActions } from "vuex";
export default {
methods: mapActions(["increment", "decrement"])};
</script>第二种是多个组件之间有多套公用数据,并且不希望进行干扰。那么就按一下方式
在src下新建store 文件夹 ,
store中新建index.js 为入口文件,modules文件夹存放各个公共数据的js文件
js 的写法
const state = { money: 1}
const mutations = {
add(state) {
state.money++
},
reduce(state) {
state.money--
}
}
const actions = {
add: ({ commit }) => {
commit('add')
},
reduce: ({ commit }) => {
commit('reduce')
}
}
export default { namespaced:true, state, mutations, actions}index.js
import Vue from 'vue'
import Vuex from 'vuex'
import money from './modules/a'
import count from './modules/b'
Vue.use(Vuex)
// 导出按照模块
export default new Vuex.Store({ modules: { money, count }})子页面的引用
<template>
<div>
a 页面的状态管理 {{$store.state.money.money}}
// 注意第一个money是模块的名字,第二个是参数
<div @click="add">增加</div>
<div @click='reduce' >减少</div>
</div>
</template>
<script>
import { mapActions } from "vuex";
export default {
methods: mapActions("money", ["add", "reduce"])
// mapActions 中的第一个参数是 模块的名字 数组是函数名};
</script>
注意点
1 、子页面的 $store.state.xxx 虽然没有放在data中,但是存放中computed中。
2 、 多个共有文件需要按照模块的方式引入并且使用