天天看點

vuex2.0基本使用---3、終極版

1、初始化項目:vue init webpack vuex_demo

2、安裝vuex:npm install vuex -D

3、在src檔案夾裡建立一個vuex檔案夾

4、在vuex檔案夾裡依次建立一個index.js、actions.js、mutations.js、mutations-types.js、 getters.js。

5、在index.js裡寫上以下代碼:

import Vue from 'vue'
import Vuex from 'vuex'

import actions from './actions'
import mutations from './mutations'

Vue.use(Vuex)

export default new Vuex.Store({
  modules: { mutations },
  actions
})
           

6、在actions.js裡寫上以下代碼:

import * as types from './mutation-types'

// 處理業務邏輯
const actions = {
  INCREMENT: (context) => {
    context.commit(types.INCREMENT)
  },
  DECREMENT: (context) => {
    context.commit(types.DECREMENT)
  },
  INCREMENTTWO: (context) => {
    context.commit(types.INCREMENTTWO)
  }
}

export default actions
           

7、在mutations.js裡寫上以下代碼:

import { INCREMENT, DECREMENT, INCREMENTTWO } from './mutation-types'
import getters from './getters'

// 處理狀态(資料)變化
const mutations = {
  [INCREMENT]: state => state.count++,
  [DECREMENT]: state => state.count--,
  [INCREMENTTWO]: (state) => {
    state.count = state.count + 2
    return state.count
  }
}

const state = {
  count: 20
}

export default {
  mutations: mutations,
  state: state,
  getters: getters
}
           

8、在mutations-types.js裡寫上以下代碼:

export const INCREMENT = 'INCREMENT'
export const DECREMENT = 'DECREMENT'
export const INCREMENTTWO = 'INCREMENTTWO'
           

9、在getters.js裡寫上以下代碼:

const getters = {
  count (state) {
    return state.count
  }
}

export default getters
           

10、在main.js裡加上以下代碼:

import Vue from 'vue'
import App from './App'
import router from './router'

import Vuex from 'vuex'
import store from './vuex/'

Vue.use(Vuex)

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  store,
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})
           

11、在components檔案夾裡建立一個Count.vue元件

12、在Count.vue元件寫上以下代碼:

<template>
  <div>
    <p>{{ count }}</p>
    <p>
      <button @click="increment()">+</button>
      <button @click="decrement()">-</button>
      <button @click="decrementTwo()">+2</button>
    </p>
  </div>
</template>

<script>
import {mapActions, mapGetters} from 'vuex'
export default {
  name: 'Count',
  methods: {
    // 對象寫法:
    ...mapActions({
      increment: 'INCREMENT',
      decrement: 'DECREMENT',
      decrementTwo: 'INCREMENTTWO'
    })
  },
  computed: {
    // 對象寫法:
    ...mapGetters({
      count: 'count'
    })
  }
}
</script>
           

12、啟動項目就可以檢視效果了