Vuex的使用

新建文件夹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
    },
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值