1. 公用模塊
1.1)定義一個專用的模塊,用來組織和管理這些全局的變量,在需要的頁面引入。
在 uni-app 項目根目錄下創(chuàng)建 common 目錄,然后在 common 目錄下新建 utils.js 用于定義公用的方法。
const baseUrl = 'http://uniapp.dcloud.io';
const nowTime = Date.now || function () {
return new Date().getTime();
};
export default {
baseUrl,
nowTime,
}
1.2)接下來在 pages/index/index.vue 中引用該模塊
<script>
import helper from '../../common/utils.js';
export default {
data() {
return {};
},
onLoad(){
console.log('nowTime:' + utils.nowTime());
},
methods: {},
}
</script>
小結(jié):
1)優(yōu)點:這種方式維護起來比較方便;
2)缺點:需要每次都引入;
2. 掛載 Vue.prototype
將一些使用頻率較高的常量或者方法,直接擴展到 Vue.prototype 上,每個 Vue 對象都會“繼承”下來。
2.1)在 main.js 中掛載屬性/方法
Vue.prototype.websiteUrl = 'http://uniapp.dcloud.io';
Vue.prototype.nowTime = Date.nowTime || function () {
return new Date().getTime();
};
2.2)在 pages/index/index.vue 中調(diào)用
<script>
export default {
data() {
return {};
},
onLoad(){
console.log('now:' + this.nowTime());
},
methods: {},
}
</script>
這種方式,只需要在 main.js 中定義好即可在每個頁面中直接調(diào)用。
Tips:
1)每個頁面中不要在出現(xiàn)重復(fù)的屬性或方法名。
2)建議在 Vue.prototype 上掛載的屬性或方法,可以加一個統(tǒng)一的前綴。比如 $baseUrl,在閱讀代碼時也容易與當前頁面的內(nèi)容區(qū)分開。
3. Vuex
Vuex 是一個專為 Vue.js 應(yīng)用程序開發(fā)的狀態(tài)管理模式。它采用集中式存儲管理應(yīng)用的所有組件的狀態(tài),并以相應(yīng)的規(guī)則保證狀態(tài)以一種可預(yù)測的方式發(fā)生變化。
3.1)在 uni-app 項目根目錄下新建 store 目錄,在 store 目錄下創(chuàng)建 index.js 定義狀態(tài)值
const store = new Vuex.Store({
state: {
login: false,
token: '',
avatarUrl: '',
userName: ''
},
mutations: {
login(state, provider) {
console.log(state)
console.log(provider)
state.login = true;
state.token = provider.token;
state.userName = provider.userName;
state.avatarUrl = provider.avatarUrl;
},
logout(state) {
state.login = false;
state.token = '';
state.userName = '';
state.avatarUrl = '';
}
}
})
3.2)在 main.js 掛載 Vuex
import store from './store'
Vue.prototype.$store = store
3.3)在 pages/index/index.vue 使用
<script>
import {
mapState,
mapMutations
} from 'vuex';
export default {
computed: {
...mapState(['avatarUrl', 'login', 'userName'])
},
methods: {
...mapMutations(['logout'])
}
}
</script>