###### tags: `VUE` VUEX 建立與安裝 === ###### tags: `Templates` `Meeting` ![](https://i.imgur.com/SvrT0sA.png) VUEX 特色就是把所有的資料或方法全部移到 VUEX 裡面做管理,無論是哪個元件都可以呼叫裡面的資料或是方法,並且可以維持 Vue 的雙向綁定特性,那麼存在 VUEX 裡面的方法我們都稱為 store 。 --- ## VUEX 4 大方法 ![](https://i.imgur.com/7eig45L.png) - state 就像元件中的 data 它是管理資料的地方 - action 就像元件中的 methods 它可以處理非同步的事件、取得遠端的資料(API) - getter 就像元件中的 computed 它在資料呈現於畫面之前可以過濾或是作加減的方法 - mutation 改變資料內容的方法 ![](https://i.imgur.com/ImwXxTT.png) ## 安裝 VUEX 以下是有裝 VUE CLI 的範例 ``` npm install vuex --save ``` ### main.js ```=javascript import Vue from 'vue' import Vuex from 'vuex' import store from './store'; // 匯入 store Vue.use(Vuex) new Vue({ router, store, // 加入這行 render: (h) => h(App), }).$mount('#app'); ``` ### store -> index.js 在 src 建立 store 資料夾,在資料夾裡面建立 index.js ![](https://i.imgur.com/178Rf63.png) ```=javascript import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); export default new Vuex.Store({ strict: true, // 嚴謹模式 state: { }, actions: { // 操作行為,不能改變資料狀態,非同步行為 setTimeout、AJAX 寫在這裡 }, mutations: { // 操作狀態,不能寫非同步行為 setTimeout、AJAX ,後續會難以除錯 }, getters: { }, modules: { }, }); ``` ### strict: true 嚴謹模式 不要再 mutations 以外的地方嘗試修改 store.state 裡面的狀態,如果你用此方式修改 Vue Tool 裡面是無法偵測到 mutations 執行的狀態,**<font color="red">所以強烈建議開啟</font>** ![](https://i.imgur.com/dtiqW3t.png)