## 一、概念
vuex是一個專門為vue.js應用程序開發的狀態管理模式。
## 二、應用場景
vue多個組件之間需要共享數據或狀態
## 三、關鍵規則

## 四、使用
#### 1、首先在根目錄下新建store文件夾
#### 2、然后再store文件夾下面創建index.js文件
#### 3、編寫代碼
實例一普通版:
```
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state:{
username:"未登錄用戶"
},
mutations:{
MLOGIN(state,username){
// 修改全局的狀態
state.username = username
},
MLOGOUT(state){
// 修改全局的狀態
state.username = '退出用戶'
}
},
actions:{ // 異步獲取方法
login(context,username){
context.commit('MLOGIN',username)
},
logout(context){
context.commit('MLOGOUT')
}
}
})
export default store
```
實例二緩存版:
```
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state:{
username:uni.getStorageSync('username')? uni.getStorageSync('username'):"未登錄用戶"
},
mutations:{
MLOGIN(state,username){
//記錄緩存
uni.setStorageSync('username',username)
// 修改全局的狀態
state.username = username
},
MLOGOUT(state){
//清除緩存
uni.clearStorageSync()
// 修改全局的狀態
state.username = '退出用戶'
}
},
actions:{ // 異步獲取方法
login(context,username){
context.commit('MLOGIN',username)
},
logout(context){
context.commit('MLOGOUT')
}
}
})
export default store
```
#### 4、掛載調用main.js中
```
import Vue from 'vue'
import App from './App'
Vue.config.productionTip = false
App.mpType = 'app'
// 調用store vuex 狀態管理
import store from '@/store/index.js'
const app = new Vue({
...App,
store
})
app.$mount()
```
#### 5、使用
實例一:
```
<template>
<view>
用戶列表
<view class="">{{username}}</view>
</view>
</template>
<script>
import {
mapState,
mapActions
} from 'vuex'
export default {
data() {
return {
}
},
onLoad() {
uni.$on('getinfosss', ()=>{
console.log('user組件中的全局事件被觸發')
})
},
computed:{
...mapState(['username'])
},
methods: {
...mapActions(['login','logout'])
}
}
</script>
<style>
</style>
```
實例二修改狀態:
```
<template>
<view>
用戶列表
<view class="">{{username}}</view>
<button class="" @click="login('登錄成功')">登錄</button>
<button class="" @click="logout">退出</button>
</view>
</template>
<script>
import {
mapState,
mapActions
} from 'vuex'
export default {
data() {
return {
}
},
onLoad() {
uni.$on('getinfosss', ()=>{
console.log('user組件中的全局事件被觸發')
})
},
computed:{
...mapState(['username'])
},
methods: {
...mapActions(['login','logout'])
}
}
</script>
<style>
</style>
```