Vuex实际应用

252 阅读1分钟

目录结构

src
|  --store
|    --index.js
|    --mutations-type.js
|  --main.js

初始化 index.js

// 1. npm i vuex

// 2. 配置
import Vue from 'vue'
import Vuex from 'vuex'

import {INCREMENT_WIDTH_DATA, INCREMENT_SUM, COUNT_SUM} from './mutations_type'

// 3. 创建容器实例
const store = new Vuex.Store({
    state: {},
    getters: {},
    mutations: {},
    actions: {}
})

// 4. 导出 store
export default store

// 5. 在main.js 中配置 store
// main.js
import Vue from 'vue'
import App from './App.vue'
import store from './store'

new Vue ({
    store, // 配置store
    render:h => h(App)
}).$mount('#app')

mutation-types.js

export const INCREMENT_WITH_DATA = 'INCREMENT_WITH_DATA'
export const INCREMENT_SUM = 'INCREMENT_SUM'
export const Count_SUM = 'COUNT_SUM'

state

  • store 中的sate类似于组件中的data
  • 任何组件都可以通过 this.$store.state.xxx 访问数据
  • 应用:
    1. 在组件中:this.$store.state.xxx
    1. 在组件中:mapState,使用对象扩展运算符将state混入computed中
    1. 非组件(.js):import store from 'xxx/store'
state: {
    sum: 1,
    count: 0,
    message: 'Vuex!',
    todos: [
        {id:1, text: '...', done: true},
        {id:2, text: '...', done: false}
    ]
}

getters

  • store中的getters类似于组件中的computed
  • getters中的函数默认接收一个参数:state,也可以接收getters本身
  • 组件中应用:
    1. store.getters.xxx
    1. mapGetters,使用对象扩展运算符将getters混入computed中
getters: {
    reverseMsg(state) {
        return state.message.split('').reverse().join('')
    },
    [COUNT_SUM](state, getters) {
        return getters.reverseMsg.length
    }
}

mutations

  • store中的mutations类似于组件中的methods
  • 只能通过mutations中的函数来修改state中的数据
  • mutations中的函数默认接收一个参数:state
  • 应用:
    1. $store.commit('函数名')
    1. mapMutations,使用对象扩展运算符将mutations混入methods
  • 注:不要在mutations中执行异步操作
mutations: {
    increment: state => {
        state.count++
    },
    increment1: (state, data) => {
      console.log(data)
      state.count += data.count
    },
    incrementData: (state, data) => {
        state.count+= data.count
    },
    [INCREMENT_WIDTH_DATA]: (state, data) => {
        state.count += data.count
    },
    [INCREMENT_SUM]:(state, data) => {
        state.sum = data.sum
    }
}

actions

  • actions类似于store中的mutations
  • 主要作用,代替mutations执行异步操作,然后将数据交给mutations修改state中的数据
  • actions中的函数默认接收一个参数 context === state
  • 应用:
    1. $store.dispatch('函数名')
    1. mapActions,使用对象扩展运算符将actions混入methods
actions: {
    increment (context, data) {
      setTimeout(() => {
        // context.state.count++
        if(data) {
          context.commit('increment1', data)
        }else {
          context.commit('increment')
        }
      }, 1000)
    },
    [INCREMENT_SUM] (context, data) {
        setTimeout(() => {
            context.commit(INCREMENT_SUM, data)
        })
    }
}

应用

state

// html
<h3>组件</h3>
<p>{{$store.state.count}}</p> // 直接调用
<p>computed count:{{count}}</p> // computed
<p>computed count:{{count1}}</p> // 使用mapsState
<p>computed countAlias:{{countAlias}}</p> // 使用mapsState,起别名
<p>computed countPlusLocalState:{{countPlusLocalState}}</p> // 使用mapsState,与组件的数据结合
// js
import {mapState} from 'vuex'
data() {
    return {
        localCount: 10
    }
}
computed: {
    count() {
        return this.$store.state.count
    },
    ...mapState({
        count1: state => state.count,
        countAlias: 'count',
        countPlusLocalState(state) {
            return state.count+this.localCount
        }
    })
}

getters

// html
<p>getters reverseMsg: {{$store.getters.reverseMsg}}</p>
<p>computed reverseMsg: {{reverseMsg}}</p> // mapGetters
<p>{{reverseLength}}</p> // mapGetters
// js
import {mapGetters} from 'vuex'
import {COUNT_SUM} from '@store/mutation-types'

computed: {
    ...mapGetters({
        reverseMsg: 'reverseMsg',
        // 使用大写常量代替字符串,防止出错
        reverseLength: COUNT_SUM
    })
}

mutations

// html
<button @click="$store.commit('incrementData',{count:10})">mutations-最好使用对象传参</button>
<button @click="handleClick">mutations</button>
<button @click="increment({count:5})">mapMutations</button>
<button @click="incrementSum({sum: 11})">mapMutations1</button>
// js
import {mapMutations} from 'vuex'
import {INCREMENT_WITH_DATA, INCREMENT_SUM} from '@/store/mutation-types'
methods: {
    handleClick () {
        this.$store.commit({type: INCREMENT_WITH_DATA, count:10})
    },
    ...mapMutations({
        //  将 `this.increment()` 映射为 `this.$store.commit('INCREMENT_WITH_DATA')`
        increment: INCREMENT_WITH_DATA,
        incrementSum: INCREMENT_SUM
    })
}

actions

// html
<button @click="$store.dispatch("increment")">action</button>
<button @click="actionnIncrement({count:5})">mapActions</button>
<button @click="incrementSumAction({sum:22})">mapActions1</button>
// js
import {mapActions} from 'vuex'
import {INCREMENT_SUM} from '@/store/mutation-types'

methods: {
    ...mapActions({
        //将`this.actionIncrement()`映射`this.$store.dispatch('increment')`
        actionIncrement: 'increment',
        incrementSumAction: INCREMENT_SUM
    })
}

特别提示

  • 如有误欢迎指正