場景是在項目中不少地方都須要用到相同的函數,例如javascript
this.$message({
type: 'success',
message: '提示語'
})
複製代碼
若是出現次數過多,會形成書寫麻煩和代碼複雜的狀況。html
由於這裏的函數是大部分組件中均可能用到的,固利用vue的全局混合。vue
新建一個global文件:java
const globalMethods = {
methods: {
tipSuccess(msg) {
this.$message({
type: 'success',
message: msg
})
},
tipError(msg) {
this.$message({
type: 'error',
message: msg
})
},
},
}
export {
globalMethods
}
複製代碼
在新建Vue的原型中利用mixin混入(main.js中,建立vue實例前):vuex
Vue.mixin(globalMethods)
複製代碼
任意vue中使用:json
this.tipSuccess('成功提示')
複製代碼
場景是但願在全部請求的時候添加上加載動畫。服務器
首先遇到的問題是,加載動畫應該掛載在哪裏?某個組件中?這裏須要根據具體的場景看,若是你的是多組件多頁面,那麼每個全新的頁面都須要添加一個加載動畫,若是是一個單頁面應用,能夠建議添加在最外層的父組件上。例如本項目中的頁面結構:app
上方導航欄是在main.vue文件中函數
下方是總體一個retouer-view,所以咱們若是須要在全部頁面中添加加載動畫,能夠直接寫在main.vue中fetch
// 利用 elementUi的 v-loading
<template>
<div class="main" v-loading="this.$store.state.isRequesting">
<h3>
<i class="el-icon-menu"> </i> 舜新建材公司庫存管理系統</h3>
<keep-alive>
<router-view></router-view>
</keep-alive>
</div>
</div>
</template>
複製代碼
上方代碼中用到的this.$store.state.isRequesting就是咱們實現全局請求添加加載動畫的核心方法:利用vuex。
首先在新建store文件夾,index.js文件:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const state = {
isRequesting: false,
isError: false
}
const mutations = {
saveIsRequesting(state, isRequesting) {
state.isRequesting = isRequesting;
},
saveIsError(state, isError) {
state.isError = isError;
},
}
const actions = {
setIsRequesting({
commit
}, isRequesting) {
commit('saveIsRequesting', isRequesting);
},
setIsError({
commit
}, isError) {
commit('saveIsError', isError);
},
}
export default new Vuex.Store({
state,
actions,
mutations
})
複製代碼
上方代碼的做用是新建了一個vuex的store,而且添加了兩個變量isRequestin和isError,分別用來標記是否須要提示正在請求(加載動畫),和是否請求出錯(提示服務器錯誤),請求成功的提示場景比較多,因此須要在代碼中本身實現。
記得在新建Vue實例的時候注入store:
new Vue({
el: '#app',
router,
store,
components: {
App
},
template: '<App/>'
})
複製代碼
而後須要在本身封裝的請求函數中添加對這兩個變量的控制,本項目中是封裝的fetch.js:
// 關鍵代碼
import store from '../store/index'
try {
// 在請求開始和結束時改變狀態
store.dispatch('setIsRequesting', true)
const response = await fetch(url, requestConfig);
const responseData = await response.json();
store.dispatch('setIsRequesting', false)
return responseData;
} catch (err) {
// 錯誤時改變狀態
store.dispatch('setIsRequesting', false)
store.dispatch('setIsError', true)
throw new Error(err)
}
複製代碼
而後就能夠在main中實現自動提示了。
自動加載動畫能夠依賴ElementUI用v-loading實現:
v-loading="this.$store.state.isRequesting"
複製代碼
服務器錯誤提示須要本身手動實現,這裏利用了vue的computed和watch兩個鉤子函數:
computed: {
isError() {
return this.$store.state.isError;
}
},
watch: {
isError(newVal) {
if (newVal) {
this.tipError('服務器出錯啦T.T');
// 顯示完後重置爲false
this.$store.dispatch('setIsError', false);
}
}
}
複製代碼
至此,咱們的請求提示封裝就完成了,最終實現的效果是在任何請求發出時都會自動出現加載動畫,而且在請求出錯時提示服務器錯誤,不須要在每個請求的時候都try..catch了。
場景是兩個不相關的組件須要通訊,由於不是父子組件關係固不能利用this.$emit來傳遞。
固利用了vue提供的事件bus。
新建一個bus.js文件
import Vue from 'vue';
export default new Vue();
複製代碼
在須要監聽事件的組件中:
import Bus from '../util/bus';
Bus.$on('eventName', this.handle);
複製代碼
觸發事件的組件中:
import Bus from '../util/bus';
Bus.$emit('refreshGoodList');
複製代碼