iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 29
0
自我挑戰組

Vue 學習筆記 - 讓你30天掌握 Vue系列 第 30

Day 29 : Vuex 計數器範例

Vuex 計數器範例

相信昨天介紹完了 Vuex 後還是會有很多人不知道該如何使用,今天就用實際範例來介紹 Vuex 究竟該如何使用,直接看下面的範例吧!

安裝 Vuex

首先,先用 npm 來安裝 Vuex。

npm install vuex --save

再來要在 main.js 啟用 Vuex,並且先 import 我們等一下會建立的 store 資料夾。

//src/main.js

import Vue from "vue";
import Vuex from 'vuex';
import App from "./App";
import store from './store';

Vue.use(Vuex);
Vue.config.productionTip = false;

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

然後我們再到 src 底下建立 store 的資料夾,並在裡面建立 index.js 的檔案,並在裡面先做基本的配置。

//src/store/index.js

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

Vue.use(Vuex);

export default new Vuex.Store({
  
})

到目前為止,基本配置已經差不多了,接下來就來實做一個計數器。

//src/components/HelloWorld.vue

<template>
  <div class="hello">
    <p>{{count}}</p>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  data() {
    return {
      counting: 10
    };
  },
  computed: {
    count() {
      return this.$store.state.count
    }
  },
};
</script>
//src/store/index.js

export default new Vuex.Store({
  state: {
    count: 1
  },
})

這時就可以正確顯示預設的數字在頁面上囉!
再來我們可以新增一個按鈕,但在事件的處理上會和原本元件的方式不太一樣。

//src/components/HelloWorld.vue

<template>
  <div class="hello">
    <p>{{count}}</p>
    <button @click="increase">Click Me</button>
  </div>
</template>

<script>

export default {
  name: "HelloWorld",
  data() {
    return {
      counting: 10
    };
  },
  computed: {
    count() {
      return this.$store.state.count
    }
  },
  methods: {
    increase() {
      this.$store.dispatch('incrementCount', this.counting)
    }
  }
};
</script>

這裡我們不在 methods 裡直接計算,而是利用 dispatch 的方式觸發 actions 裡的事件。

//src/store/index.js

export default new Vuex.Store({
  state: {
    count: 1
  },
  actions: {
    incrementCount(context, counting){  //context 後方可以帶入要傳入的參數,如果沒有參數可以省略。
      context.commit('INCREMENT_COUNT', counting)
    }
  },
  mutations: {
    INCREMENT_COUNT(state, counting) {  //state 後方可以帶入要傳入的參數,如果沒有參數可以省略。
      state.count += counting
    }
  }
})

actions 的事件被觸發後,會靠 commit 去呼叫 mutations 裡的方法,並且在 mutations 去改變 state 裡的資料內容,這時就可以正確地增加計數器的數字囉!

雖然可以正常運作,但是這樣的配置方式並不理想!這只是先方便讓大家閱讀並理解而已,明天我們來將它改為正確的配置。

那麼,明天再見囉!


上一篇
Day 28 : Vuex
下一篇
Day 30 : Vuex 計數器範例 - 2
系列文
Vue 學習筆記 - 讓你30天掌握 Vue31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言