vuex 使用案例

vuex主要应用于vue.js中管理数据状态的一个库,通过创建一个集中的数据存储,供程序中所有组件访问。 需根据项目规模进行判断是否使用,这并不是一定要使用的!
组件之间传值可以使用emit,但随着页面组件越来越多,涉及到的数据传递就会麻烦,vuex的优势就体现出来了。(页面刷新会丢失,可对其写应付方法)
常规设计store对象包含四个属性:state、getters、actions、mutations

state 数据储存 (类似存储全局变量的数据)
getters 数据获取 (提供用来获取state数据的方法)
actions 事件驱动 (提供跟后台接口打交道的方法,并调用mutations提供的方法)
mutations 数据改变 (提供存储设置state数据的方法)

image.png

1.组件Vue component通过dispatch 调用actions提供的方法
2.actions除了可以和api打交道外,还可以通过commit来调用mutations提供的方法
3.mutaions将数据保存到state中
4.Vue components 还可以通过getters提供的方法获取state中的数据
mapGetters 一般也写在 computed 中 , mapActions 一般写在 methods中

state

  • 单一状态数,用一个对象就包含了全部的应用层级状态
  • mapState 当一个组件需要获取多个状态时,将这些状态都声明为计算属性会有些重复和冗余
  • ...mapState({})
import { mapState } from 'vuex'
dexport default {
    computed: mapState({
        count: state => state.count,
        countAlias: 'count',
        countPlusLocalState (state) {
            return state.count + this.localCount
        }
        // ...mapState({count}) 扩展函数符
    })
}

getters

  • 从store中的state中派生出一些状态
  • mapGetters 辅助函数仅仅是将store总的getters映射到局部计算属性
  • 对state进行扩展,通过getters进行设置(相当于computed,可以认为是store的计算属性)公用的一些方法
computed: {
    doneTodosCount () {
        return this.$store.getters.doneTodos
    },
    ...mapGetters([
        'doneTodosCount'
    ])
}

mutations

  • 更改vuex的store中的状态,唯一方法是提交mutation(不能直接调用句柄,必须通过触发)
  • mutations就是vue methods
  • 每个mutation都是一个字符串的时间类型(type)和一个回调函数(handler)
  • 使用常量代替mutation事件类型
  • mutation必须是同步函数
//mutation-types.js
export const SOME_MUTATION = 'SOME_MUTATION'

//store.js
import { SOME_MUTATION } from './mutation-types'

const store = new Vuex.Store({
    state:{...},
    mutations:{
        [SOME_MUTATION](state){
            //mutate state
        }
    }
})

Mutations(调用篇)

import { mapMutations } from 'vuex'
import { SOME_MUTATION } from './mutation-types'

export default {
    methods:{
        test(){
            this.$store.commit(SOME_MUTATION)
        },
        ...mapMutations([
            'SOME_MUTATION'
            //映射 this.increment()为this.$store.commit('SOME_MUTATION')
        ])
    }
}

actions

  • 接受用户传过来的event
  • 提交的是mutation
  • 可以包含任何异步操作
  • mapActions辅助函数将组建的methods映射为store.dispatch调用
  • view -> store.dispathc('increment')
  • action -> commit('someMutation')
actions: {
  async actionA({commit}) {
    commit('gotData', await getData())
  },
  async actionB({dispathc, commit}) {
    await dispathc('actionA')// 等待actionA完成
    commit('getOtherData'(), await getOtherData())
  }
}
//Action 调用
import { mapActions } from 'vuex'
export default {
    methods:{
        test(){
            store.dispatch('actionB')
        }
    },
    ...mapActions([
        'actionB'
        //映射 this.increment()
        //this.$store.dispatch('actionB')
    ])
}

实际项目简单使用

store
  ├── actions.js
  ├── getters.js
  ├── index.js
  ├── mutations.js
  ├── state.js
  ├── types.js
//index.js
import Vue from 'vue'
import Vuex from 'vuex'
import actions from './actions'
import getters from './getters'
import state from './state'
import mutations from './mutations'
Vue.use(Vuex)

export default new Vuex.Store({
  actions,
  getters,
  state,
  mutations
})
//actions.js
import * as types from './types'
const actions = {
  saveCurrentDirect ({commit, state}, obj) {
    commit(types.DIRECTIONAL_SCREEN_CONDITION, obj)
  }
}
export default actions
//getters.js
const getters = {
  // 当前储存的资讯
  currentDirect (state) {
    return state.saveCurrentDirect.data
  }
}

export default getters

//mutations.js
import * as types from './types'

const mutations = {
  // 定向筛选条件
  [types.DIRECTIONAL_SCREEN_CONDITION] (state, payload) {
    state.saveCurrentDirect.data = payload
  }
}

export default mutations
//state.js
const state = {
  // 定向筛选条件
  saveCurrentDirect: {
    data: null
  }
}

export default state
//types.js
// 定向筛选条件
export const DIRECTIONAL_SCREEN_CONDITION = 'DIRECTIONAL_SCREEN_CONDITION'
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 安装 npm npm install vuex --save 在一个模块化的打包系统中,您必须显式地通过Vue.u...
    萧玄辞阅读 7,991评论 0 7
  • Vuex是什么? Vuex 是一个专为 Vue.js应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件...
    萧玄辞阅读 8,301评论 0 6
  • ### store 1. Vue 组件中获得 Vuex 状态 ```js //方式一 全局引入单例类 // 创建一...
    芸豆_6a86阅读 4,021评论 0 3
  • vuex 场景重现:一个用户在注册页面注册了手机号码,跳转到登录页面也想拿到这个手机号码,你可以通过vue的组件化...
    sunny519111阅读 12,443评论 4 111
  • Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应...
    白水螺丝阅读 10,106评论 7 61