vue是一個專為 Vue.js 應用程序開發(fā)的狀態(tài)管理模式。它采用集中式存儲管理應用的所有組件的狀態(tài),并以相應的規(guī)則保證狀態(tài)以一種可預測的方式發(fā)生變化。Vuex 也集成到 Vue 的官方調試工具 devtools extension,提供了諸如零配置的 time-travel 調試、狀態(tài)快照導入導出等高級調試功能。
示例如下:
(1) 在根目錄下創(chuàng)建 stroe/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
// 創(chuàng)建一個 store
const store = new Vuex.Store({
// (1)初始 state 對象
state:{
hasLogin: false,
token: "",
company:"未知",
userInfo: {
"name": "未知",
"role": "未知",
"age": 0
},
},
// (2)定義一些mutation
mutations:{
change(state,company){
state.company = company;
},
login(state,token,userInfo) {
state.hasLogin = true;
state.token = token;
state.userInfo = userInfo;
},
logout(state) {
state.hasLogin = false;
state.token = "";
},
celarUserInfo(state) {
state.userInfo = {
"name": "",
"role": "",
"age": 0
};
},
}
})
// 導出該模塊:以便其他文件可對其進行使用
export default store
在JavaScript ES6中,export與export default均可用于導出常量、函數(shù)、文件、模塊等;并在其它文件或模塊中通過import+(常量 | 函數(shù) | 文件 | 模塊)名的方式將其導入,以便能夠對其進行使用;但在一個文件或模塊中,export、import可以有多個,export default僅有一個。
(2) 在main.js中掛在Vuex
import store from './store'
Vue.prototype.$store = store;
(3) 獲取狀態(tài)對象與觸發(fā)狀態(tài)變更
<template>
<view>
<text>名稱:{{company}}</text>
<button type="primary" @tap="onChange()">更改</button>
</view>
</template>
<script>
import {mapState,mapMutations} from 'vuex';
export default {
data() {
return {
}
},
computed:{
...mapState(['company'])
},
methods: {
onChange : function(){
this.$store.commit('change', 'jk');//通過 store.commit 方法觸發(fā)狀態(tài)變更
}
},
onLoad() {
}
}
</script>
<style>
</style>
說明:使用 Vuex 保證了變量在全局的統(tǒng)一性,可以在實際開發(fā)中進行對應場景的應用。