新建文件夹store,index.js,actions.js(异步操作),getters.js(计算属性),mutations(方法),mutation-types.js(统一变量名称页面),modules文件夹下modulesA.js。
1.index.js
import Vue from 'vue'
import Vuex from 'vuex'
import { INCREMENT } from './mutation-types'
import mutations from './mutations'
import actions from './actions'
import getters from './getters'
import modulesA from './modules/modulesA'
// 1.安装插件
Vue.use(Vuex)
// 2.创建modules的对象
const moduleA = modulesA
// 3.创建一个Vuex的对象
// Vuex响应式规则
// 01.提前在store中初始化好所需的属性
// 02.给state的对象添加新属性时,使用一下方式。{(使用Vue.set(obj,'newProp',123)) (用新对象给旧对象重新赋值)}
const store = new Vuex.Store({
// 保存共享状态(数据储存)
state: {
counter: 1000,
students: [
{id: 110, name: 'why', age: 18},
{id: 111, name: 'liu', age: 20},
{id: 112, name: 'Bob', age: 30},
{id: 113, name: 'luyi', age: 40},
],
info: {
name: 'justion',
age: 27,
height: 183
}
},
mutations,
actions,
getters,
// 用于不同模块状态的保存
modules: {
a: moduleA
}
// 4.导出store对象
export default store
2.moduleA.js
文件中可以存放某个模块特有的状态
3.mutation-types.js
// 统一变量名称页面,用常量
export const INCREMENT = 'increment'
4.actions.js(异步)
actions.js的方法调用,this.$store.dispatch(‘aupdataInfo’, 参数)
export default {
aupdataInfo(context,payload) { // 默认属性context(上下文),理解为state对象
return new Promise((resolve,reject) => {
setTimeout(() => {
context.commit('updateinfo')
console.log(payload);
resolve('111111')
},1000)
})
}
}
5.mutations.js
mutations.js的方法调用,this.$store.commit(‘aupdataInfo’, 参数)
import { INCREMENT } from "./mutation-types";
[INCREMENT](state) { // 默认有一个参数叫state
state.counter++
},
updateinfo(state) {
state.info.name = 'code'
}
6.getters.js
export default {
powerCounter(state) {
return state.counter * state.counter
},
}