vuex的使用和封装

vuex是一个状态管理工具,可以实现数据的响应式,
看下图
在这里插入图片描述

vuex主要是有五个属性,state,actions,getters,mutations,modules,

state主要是声明变量;

通过this.$store.state.属性的方式来访问状态

mutations是一个方法,也可以传递两个参数

通过this.$store.commit(‘mutation中方法’)来修改状态
当传递两个参数时,

//第二个是值
store.commit('increment', 10)
//在mutations中这样使用
mutations: {
  increment (state, n) {
    state.count += n
  }
}
//当第二个参数是对象的时候
store.commit('increment', {
  amount: 10
})

mutations: {
  increment (state, payload) {
    state.count += payload.amount
  }
} 
//还可以如此
store.commit({
  type: 'increment',
  amount: 10
})
mutations: {
  increment (state, payload) {
    state.count += payload.amount
  }
}

actions通常发送异步请求

方法调用


actions: {
  incrementAsync ({ commit }) {
    setTimeout(() => {
      commit('increment')
    }, 1000)
  }
}

可以如此
store.dispatch('increment')

// dispatch with a payload
store.dispatch('incrementAsync', {
  amount: 10
})

// dispatch with an object
store.dispatch({
  type: 'incrementAsync',
  amount: 10
})

module
const moduleA = {
state: () => ({ … }),
mutations: { … },
actions: { … },
getters: { … }
}

const moduleB = {
state: () => ({ … }),
mutations: { … },
actions: { … }
}

const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
})

store.state.a // -> moduleA's state
store.state.b // -> moduleB's state

getters是一个处理数据的

调用方法
store.getters.doneTodos // -> [{ id: 1, text: '...', done: true }

const store = new Vuex.Store({
  state: {
    todos: [
      { id: 1, text: '...', done: true },
      { id: 2, text: '...', done: false }
    ]
  },
  getters: {
    doneTodos: state => {
      return state.todos.filter(todo => todo.done)
    }
  }
})

modules是模块,

const moduleA = {
  state: () => ({ ... }),
  mutations: { ... },
  actions: { ... },
  getters: { ... }
}

const moduleB = {
  state: () => ({ ... }),
  mutations: { ... },
  actions: { ... }
}

const store = new Vuex.Store({
  modules: {
    a: moduleA,
    b: moduleB
  }
})

store.state.a // -> `moduleA`'s state
store.state.b // -> `moduleB`'s state

最后我们创建项目中步骤:
先安装vuex:npm install vuex --save
然后是创建文件夹:store,index.js文件
![目录结构](https://img-blog.csdnimg.cn/20210719172016453.png#pic_center在这里插入图片描述

然后每个文件的内容
index.js

import Vue from 'vue'
import Vuex from 'vuex'
import mutations from './mutations'
import getters from './getters'
import actions from './actions'

Vue.use(Vuex)

const state = {
	cartList: []
}

const store = new Vuex.Store({
	state,
	mutations,
	getters,
	actions
})

export default store
//actions 
const actions = {

}

export default actions

//getters 
const getters = {
}
export default getters

//mutations 
const mutations = {
}


export default mutations

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值