F2E 拉賽 Vuex


What is Vuex ?

  • 單向資料流
  • Flux design pettern
  • 統一管理應用程式所有狀態

Vuex = 狀態管理模式

F2E 拉賽 - Vuex flow


狀態管理模式-官方 vue 計數器說明

new Vue({ // state data () { return { count: 0 } }, // view template: ` <div>{{ count }}</div> `, // actions methods: { increment () { this.count++ } } })

Vuex flow

F2E 拉賽 - Vuex flow


Vuex Install

Vuex git
Vuex gitbook

npm install vuex --save

建立資料結構

├─src
│  ├─components
│  ├─router
│  ├─store (new)
│  │  └─index.js (必備預設檔名)
│  └─main.js

store/index.js

import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const state = {} const getters = {} const actions = {} const mutations = {} export default new Vuex.Store({ state, getters, actions, mutations })

main.js

... import store from './store'; new Vue({ el: '#app', router, // 加入 store store, template: '<App/>', components: { App } })

角色分析

腳色 職權
state 存放 APP 所有 state
action 調用 mutation 函式及處理 ajax (非同步)
getter 負責取 state 資料
mutation 負責改變 state 資料 (同步)

在 Vue 使用 Vuex Action

import { mapActions } from 'vuex' export default { // ... methods: { // 方法一 直接取用 ...mapActions([ 'increment' ]), // 方法二 另存別名取用 ...mapActions({ add: 'increment' // 使用 add 為元件內別名 }), // 方法三 直接呼叫使用 actionIncrement(){ this.$store.dispatch('increment') } } }

在 Vue 使用 Vuex Getter

import { mapGetters } from 'vuex' export default { data () { return { // 方法三 直接呼叫使用 count: this.$store.state.count } }, computed: { // 方法一 直接取用 ...mapGetters([ 'getCount' ]), // 方法二 另存別名取用 ...mapGetters({ count: 'getCount' // 使用 add 為元件內別名 }) } }

Vue 套用了 Vuex


學會 Vuex 了吧!?


Reference

Select a repo