---
# System prepended metadata

title: VueX global variable紀錄
tags: [Vue.js, ' VueX']

---

---
title: VueX global variable紀錄
tags: Vue.js, VueX
description: Use VueX to record global variable
---

# 前端Vue.js開發環境安裝 

## vuex installation

```
$ npm install — save vuex
```

---

## 在專案裡使用VueX

**檔案appendence如下**
![](https://i.imgur.com/yoKqGOw.png)


在 main.js 裡 import Vuex 和 store 的 folder 並且將 store 掛在 #app 上

**main.js**
```
import Vue from "vue";
import App from "./App";
import router from "./router/index";
import PaperDashboard from "./plugins/paperDashboard";
import "vue-notifyjs/themes/default.css";
import variable from "./router/variable.js";
import store from "./store";

Vue.prototype.GLOBAL = variable
Vue.use(PaperDashboard);
new Vue({
router,
store,
render: h => h(App)
}).$mount("#app");
```

---

## store folder
store folder 裡包含四個檔案，為定義 global varibale 的地方

### index.js
index.js為程式進入的入口，在 index.js 裡掛上 state.js、actions.js、mutations.js後續會一一介紹各個 file 內容

```
import Vue from 'vue'
import Vuex from 'vuex'
import state from ''./state'
import actions from ''./actions'
import mutations from ''./mutations'

Vue.use(Vuex)
export default new Vuex.Store({
    state,
    actions,
    mutations
})
```

### state.js

state.js 檔案為宣告初始化的 global variable

```
export default {
    callingAPI: false,
    searching: '',
    serverURI: 'http://10.101.1.20:8080',
    user: null,
    token: null,
}
```

### mutation.js

mutation.js 是回調函數(handler)，將變數儲存成global variable的地方，以下為將user, token, profile定義如何儲存參數的方法

```
export default {
    TOGGLE_LOADING (state) {
        state.callingAPI = !state.callingAPI 
    },
    TOGGLE_SEARCHING (state) {
        state.searching = (state.searching === '') ? 'loading' : ''
    SET_USER (state, user) {
        state.user = user 
    },
    SET_TOKEN (state, token) {
        state.token = token 
    },
    profile1 (state, profile) {
        state.profile = profile 
    }
}
```

### action.js

```
export default {}
```

---

## Using golbal variable in Vue

* 在其他.vue檔案下通過呼叫this.$store.commit('SET_USER', user)即可以將值儲存至global variable

```
<template>
</template>
<script>
export default {
    data() {
        return {
            usr: 'shaung08'
        }
    },
    method:{
        article() {
            this.$store.commit('SET_USER', user)
        }
    }
}
</script>
```

* 使用this.$store.state.user即可呼叫global variable的值

```
<template>
</template>
<script>
export default {
    data() {
        return {
            usr: ''
        }
    },
    method:{
        article() {
            this.usr = this.$store.state.user
        }
    }
}
</script>
```

---

## Thank you! :dash: 

You can find me on
- GitHub: https://github.com/shaung08
- Email: a2369875@gmail.com