vue.js中vuex狀態管理的實現與模組化
阿新 • • 發佈:2019-02-12
本文采用的前端元件為ElementUI,所以需要在使用vuecli搭建前端工程,後繼續安裝npm install element-ui,並在main.js中引入
main.js程式碼:
import Element from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
Vue.use(ElementUI)
新建儲存資料夾用於存放vuex相關元件,其index.js配置vuex的初始主檔案,並載入模組中的子模組,下面的模組資料夾存放子模組檔案
先展示儲存/ index.js的程式碼
import Vue from 'vue'
import Vuex from 'vuex'
//匯入vuex的store模組
import moduleOne from './modules/moduleOne'
import services from '../services/index.js'
// import flyio from 'flyio'
Vue.use(Vuex)
// 從環境變數判斷當前執行模式
// const debug = process.env.NODE_ENV !== 'production'
const store = new Vuex.Store({
// strict:debug, //設定執行模式
// plugin:debug ? [createLogger()] : [] //除錯模式則加入日誌外掛
// 引入modules中的模組
modules: {
moduleOne
},
//state相當於data
state: {
//作者名稱
author: 'FANE',
address: '江蘇南京',
school: ['北大', '清華'],
version: '版本1.1',
loginInfo: {
name: 'Zhang' ,
age: '24'
},
count: 1,
data: ['www']
},
//getters相當於computed
getters: {
author: state => state.author,
loginInfo: state => state.loginInfo,
// address:state => state.address,
// version:state => state.version,
// school:state => state.school,
count: state => state.count,
data: state => state.data,
},
// 只用mjutations修改狀態:用於操作state中狀態和改變相關資料
mutations: {
increment: state => state.count++,
decrement: state => state.count--,
dataReceive(state, res) {
state.data = res
}
},
//actions相當於methods(或者MVC中的Controller),用於操作mutations實現對state中狀態的讀取,但是actions不會直接對狀態做修改
actions: {
decrement(context) {
context.commit('decrement') // 呼叫mutations中的decrement
},
getBarData(context) {
// services.apiOne.getBarData.then(res => {
// console.log(res)
// })
services.apiOne.getBarData(function (res) {
console.log(`fly獲取到結果為:`)
console.log(res)
})
}
}
})
// 匯出store例項物件
export default store
其中的fliyio與axios類似,都是用於前後端通訊的元件;
前端程式碼Helloworld.vue,主要程式碼註釋都放在程式碼中,方便大家複製走查
<template>
<div id="helloword">
<h1 style="font-family: 'AhsanCalligraphyRegular'">Gyosho Test English</h1>
<hr>
<el-row :gutter="20">
<el-col :span="4">
<span>getters.author:{{this.author}}</span>
<br>
<span>state.version:{{this.version}}</span>
</el-col>
<el-col :span="8">
<span>mapState:{{this.school}}</span>
<br>
<span>mapState:{{this.address}}</span>
</el-col>
<el-col :span="8">
<span>mapGetters:{{this.data}}</span>
<br>
<span>mapGetters:{{this.count}}</span>
<el-button size="small" @click="add()">數字加</el-button>
<el-button size="small" @click="small()">減</el-button>
</el-col>
</el-row>
<hr>
<el-row :gutter="20">
<el-col :span="6">
<span>moduleOne.liu:{{this.liu}}</span>
<br>
<span>computed(loginInfo):{{this.loginInfo}}</span>
</el-col>
<el-col :span="18">
<el-input v-model="newName" placeholder="請輸入內容" style="width:20%"></el-input>
<el-button size="small" @click="changeNewName()">NewName</el-button>
<el-button size="small" @click="changeNameA()">改成南京</el-button>
</el-col>
</el-row>
<hr>
<el-row :gutter="10">
<el-col :xs="8" :sm="6" :md="4" :lg="3" :xl="1"><div class="grid-content bg-purple">響應式佈局</div></el-col>
<el-col :xs="4" :sm="6" :md="8" :lg="9" :xl="11"><div class="grid-content bg-purple-light"></div></el-col>
<el-col :xs="4" :sm="6" :md="8" :lg="9" :xl="11"><div class="grid-content bg-purple"></div></el-col>
<el-col :xs="8" :sm="6" :md="4" :lg="3" :xl="1"><div class="grid-content bg-purple-light"></div></el-col>
</el-row>
</div>
</template>
<script type="text/javascript">
import {mapGetters,mapActions,mapState} from 'vuex'
export default{
data() {
return {
newName:''
}
},
computed:{
//此處loginInfo是一個物件,預設執行get方法放回當前引數
loginInfo:{
get(){
return this.$store.state.loginInfo.name //state直接獲取
},
set(newValue){
this.$store.state.loginInfo.name = newValue
}
},
version(){
return this.$store.state.version //方法一:state直接獲取
},
author(){
return this.$store.getters.author //方法一:getters方法獲取
},
...mapState([ //方法二:mapState獲取
'address',
'school',
]),
...mapGetters([ //方法二:mapGetters獲取
'count',
'data'
]),
/*moduleOne中的檔案*/
liu(){
return this.$store.state.moduleOne.liu
},
},
mounted(){
this.getBarData();
},
methods: {
add(){
this.$store.commit('increment') //.commit()方法可以直接呼叫mutations的increment方法
},
small(){
this.$store.dispatch('decrement') //方法一:.dispatch()方法呼叫actions中的方法decrement,間接呼叫mutations中的decrement
},
changeNewName() {
this.loginInfo = this.newName // 修改loginInfo內容
// this.$store.commit('newName',this.newName)
this.$store.dispatch('newName', this.newName)
},
...mapActions([ // 方法二:通過mapActions將actions對映到methods中
'getBarData',
'changeNameA' //changeNameA是來自moduleOne的actions
])
}
}
</script>
<style scoped>
.el-col {
border-radius: 4px;
}
.bg-purple-dark {
background: #99a9bf;
}
.bg-purple {
background: #d3dce6;
}
.bg-purple-light {
background: #e5e9f2;
}
.grid-content {
border-radius: 4px;
min-height: 36px;
}
</style>
vuex的模組舉個例子為modules/moduleOne.js
import Vue from 'vue'
import services from '../../services/index.js'
const state = {
liu: 'jingna',
wei: ['yu', 'ning']
}
const mutations = {
changeName(state, res) {
state.liu = res
},
newName(state, res) {
console.log("moduleOne.mutations----newName")
console.log(res)
state.liu = res
}
}
const actions = {
changeNameA(context) {
context.commit('changeName', '南京')
},
newName(context, params) {
console.log(`moduleOne.actions=====${params}`)
context.commit('newName', params)
}
}
export default {
state, mutations, actions
}
還有其中的api.js主要存放前端向後端請求的介面api,也是為了程式碼的模組化,今天加班結束寫的部落格,感覺自己對vue的理解還是不夠,後期會增加對vue前端相關的測試元件等的研究,希望大家多多支援和建議!感謝閱讀