<style> .reveal section img { margin: none; background: none; border: none; box-shadow: none; max-width: 80%; } </style> # F2E 拉賽 Vuex ![](https://scontent-tpe1-1.xx.fbcdn.net/v/t31.0-8/19400601_394696257593270_2237482372163072563_o.png?oh=e3ad6ed42f5f43fe134e5f02d4edf322&oe=59DD7296) --- ## What is Vuex ? - 單向資料流 - Flux design pettern - 統一管理應用程式所有狀態 --- ## [Vuex = 狀態管理模式](https://vuex.vuejs.org/zh-cn/intro.html) ![F2E 拉賽 - Vuex flow](https://vuex.vuejs.org/zh-cn/images/flow.png) --- ### 狀態管理模式-官方 vue 計數器說明 ```javascript= new Vue({ // state data () { return { count: 0 } }, // view template: ` <div>{{ count }}</div> `, // actions methods: { increment () { this.count++ } } }) ``` --- ## Vuex flow ![F2E 拉賽 - Vuex flow](https://vuex.vuejs.org/zh-cn/images/vuex.png) --- ## Vuex Install [Vuex git](https://github.com/vuejs/vuex) [Vuex gitbook](https://vuex.vuejs.org/) ```bash npm install vuex --save ``` --- ## 建立資料結構 ``` bash ├─src │ ├─components │ ├─router │ ├─store (new) │ │ └─index.js (必備預設檔名) │ └─main.js ``` --- ## store/index.js ```javascript= 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 ```javascript= ... 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 ```javascript= import { mapActions } from 'vuex' export default { // ... methods: { // 方法一 直接取用 ...mapActions([ 'increment' ]), // 方法二 另存別名取用 ...mapActions({ add: 'increment' // 使用 add 為元件內別名 }), // 方法三 直接呼叫使用 actionIncrement(){ this.$store.dispatch('increment') } } } ``` --- ## 在 Vue 使用 Vuex Getter ```javascript= import { mapGetters } from 'vuex' export default { data () { return { // 方法三 直接呼叫使用 count: this.$store.state.count } }, computed: { // 方法一 直接取用 ...mapGetters([ 'getCount' ]), // 方法二 另存別名取用 ...mapGetters({ count: 'getCount' // 使用 add 為元件內別名 }) } } ``` --- <!-- .slide: data-background="#FFF" --> ## Vue 套用了 Vuex ![](http://cdn.ithelp.ithome.com.tw/upload/images/20161212/20103326wJ4d3Mc8Up.png) --- <!-- .slide: data-background="#FFF" --> ![](https://mraw.org/blog/2010/03/30/we-need-you.png) ### 學會 Vuex 了吧!? --- ## Reference - [Vuex git](https://github.com/vuejs/vuex) - [Vuex gitbook](https://vuex.vuejs.org/) - [vue & vuex 10 - 什麼是 vuex?](http://ithelp.ithome.com.tw/articles/10185686) - [vue & vuex 11 - 計數器 - I (vuex 職權與流程說明)](http://ithelp.ithome.com.tw/articles/10185784)
{"metaMigratedAt":"2023-06-14T13:07:15.001Z","metaMigratedFrom":"Content","title":"F2E 拉賽 Vuex","breaks":true,"contributors":"[]"}
    587 views