vue中vuex的五个属性和基本用法

VueX 是一个专门为 Vue.js 应用设计的状态管理构架,统一管理和维护各个vue组件的可变化状态(你可以理解成 vue 组件里的某些 data )。

Vuex有五个核心概念:

  state, getters, mutations, actions, modules。

  1. state:vuex的基本数据,用来存储变量

   2. geeter:从基本数据(state)派生的数据,相当于state的计算属性

   3. mutation:提交更新数据的方法,必须是同步的(如果需要异步使用action)。每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。

   回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数,提交载荷作为第二个参数。

   4. action:和mutation的功能大致相同,不同之处在于 ==》1. Action 提交的是 mutation,而不是直接变更状态。 2. Action 可以包含任意异步操作。

   5. modules:模块化vuex,可以让每一个模块拥有自己的state、mutation、action、getters,使得结构非常清晰,方便管理。

Vuex的用法:

  新建vue项目testApp ==》 在testApp中建store文件 ==》 store文件下又有modules文件夹和getter.js 和 index.js ==》 store文件下建user.js

  在项目的main.js中引入 import store from './store'

在store文件下的index.js中引入

import Vue from 'vue'

import Vuex from 'vuex'

import user from './modules/user'

import global from './modules/global'

import getters from './getters'

Vue.use(Vuex)

const store = new Vuex.Store({

modules: {

user

},

getters

})

export default store

在store文件下的getters.js中引入

const getters = {

self: state => state.user.self,

token: state => state.user.token,

currentCommunity: (state, getters) => {

let cid = getters.currentCommunityId

return getters.communities.filter(item => {

return item.communityId === cid

})

}

}

export default getters

在modules文件下的user.js写代码

const user = {

state:{

self: null,

token: '',

},

mutations:{

SET_SELF: (state, self) => {

state.self = self

},

SET_TOKEN: (state, token) => {

state.token = token

}

},

actions:{

login ({ commit }, res) {

commit('SET_SELF', res.self)

commit('SET_TOKEN', res.token

}

}

export default user

使用:

  dispatch:异步操作,写法: this.$store.dispatch('action方法名',值)

  commit:同步操作,写法:this.$store.commit('mutations方法名',值)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陽のように

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值