# vuex 簡單介紹 14 ###### tags: `vue` ## 什麼是vuex? vuex是一個好用的傳值套件,他可以無視元件之間的關係,做到跨元件傳值的功能。可以讓你很方便地管理全站共用的資料 / 狀態。 ### 基本說明: 一開始我們在新增專案時有順便加入vuex的話,專案就會有一個叫store的資料夾,裡面有一個index.js的檔案。如下圖 ![](https://i.imgur.com/UfzTHib.jpg) 右邊的程式碼是vuex的基本架構 state: 是我們的狀態列表,就是用來宣告變數的地方,但不能直接在裡面做修改 mutations: 引入state裡的資料,並做運算 actions: 用來呼叫mutations,也可呼叫另一個actions modules: store 裡面的 state 可能會變得越來越多,不方便管理,所以Modules 來解決這個問題,將store中各類的state做分類。 除了這些之外含有幾個重點: mutations 一定只能執行同步,actions 才能執行非同步。 Actions 不能直接修改 State,只有 Mutations 可以更改 State。 Dispatch 是呼叫 Actions,Commit 是呼叫 Mutations。 接下來我們用vuex來做一個簡單範例 --- ### 簡單實作: 我們先讓state的值顯示在元件上 先在state新增兩筆data ![](https://i.imgur.com/ZQo0Lvx.jpg) 接著在元件裡引入 `import { mapState } from "vuex"` 並在computed裡打 ``` ...mapState({ count: state => state.value, title: state => state.title, }), ``` ![](https://i.imgur.com/fguPZKK.jpg) state.value和state.title就是state裡的值,count和title則是為他們定義的名稱 接著在html裡放上count和title,就可以看到vuex的值顯示在畫面上了。 ``` <template> <div > <p>{{title}}{{count}}</p> </div> </template> <script> // @ is an alias to /src /*eslint-disable*/ import { mapState } from "vuex"; export default { name: 'xxx', computed: { ...mapState({ count: state => state.value, title: state => state.title, }), }, } </script> ``` --- 我們在更進一步,用mutations來修改state的值。 我們先在mutations新增一個function來修改state的值 ![](https://i.imgur.com/bTHqa5o.jpg) 然後再元件內呼叫這function,就可以更改state的值。 ![](https://i.imgur.com/XGIW7IP.jpg) 如果我們想要把累加的值寫在元件裡而不是在vuex裡,只要改成 元件: ![](https://i.imgur.com/sD0MUTF.jpg) store/index.js: ![](https://i.imgur.com/qRQt2yV.jpg) --- 我們再換另一個方式,就是用Actions來呼叫mutations改State的值 在Actions裡新增一個function,下圖表示呼叫mutations裡的 add和change function ![](https://i.imgur.com/xktBTfu.jpg) 接著在元件呼叫Actions,就成功了 ![](https://i.imgur.com/aCz86nK.jpg) --- 全程式碼 vuex ``` import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state: { title: "現在的值是:", value: 0 }, mutations: { add(state) { state.value += 1 }, change(state) { state.title = "用actions呼叫:" } }, actions: { call(context) { context.commit('add') context.commit('change') } }, modules: {} }) ``` 元件 ``` <template> <div class="home"> <p>{{title}}{{count}}</p> <br> <button @click="makeadd">add</button> </div> </template> <script> // @ is an alias to /src /*eslint-disable*/ import { mapState } from "vuex"; export default { name: 'xxx', components: { }, data:()=>({ two:2, three:3 }), methods:{ makeadd(){ // this.$store.commit('add',{totwo:this.two,tothree:this.three}) this.$store.dispatch('call') } }, computed: { ...mapState({ count: state => state.value, title: state => state.title, }), }, } </script> ```