應用場景:
使用vux的小伙伴應該能體會到,以插件形式調用的toast、loading用起來都停不錯的,只需要main.js中添加為vue的實例方法,就可以在頁面中根據需要隨時隨地的進行調用。
同樣,項目中也需要一些公用的頁面,如全局的訪問異常頁面。如果采用普通的組件引用,則需要在每個需要用到的頁面中進行引用,就比較麻煩了。
最好的就是做成像toast插件一樣能直接調用的插件,是最好的解決方法。
示例代碼:
components/error.vue
1 <template> 2 <div class="error tc" v-show="show"> 3 <Icon class="icon c_c" type="info" is-msg></Icon> 4 <p class='msg f16 c_6' :style="{'width':width}">{{msg||"訪問出錯,請返回重試!"}}</p> 5 <button @click='goToIndex' size='mini'>返回首頁</button> 6 </div> 7 </template> 8 9 <script> 10 import { Icon } from 'vux' 11 export default { 12 components: { 13 Icon 14 }, 15 props: { 16 msg: String, 17 show: Boolean, 18 width: String //百分比 19 } 20 ...... 21 } 22 </script> 23 <style scoped> 24 .error { 25 width: 100%; 26 height: 100%; 27 overflow: hidden; 28 position: fixed; 29 top: 0; 30 left: 0; 31 z-index: 9999; 32 } 33 34 .icon { 35 margin: 1.2rem auto .4rem auto; 36 font-size: 70px!important; 37 } 38 39 button { 40 margin-top: 1rem; 41 } 42 43 .msg { 44 margin: 0 auto; 45 width: 60%; 46 } 47 </style>
注:width參數用於自定義設置錯誤信息展示的寬度(默認寬度為60%,可以通過width參數進行自定義)。
components/error.js
1 import errorComp from './error.vue' 2 3 const error = {}; 4 5 // 注冊Toast 6 error.install = function(Vue) { 7 // 生成一個Vue的子類 8 // 同時這個子類也就是組件 9 const ErrorConstructor = Vue.extend(errorComp) 10 // 生成一個該子類的實例 11 const instance = new ErrorConstructor(); 12 13 // 將這個實例掛載在我創建的div上 14 // 並將此div加入全局掛載點內部 15 instance.$mount(document.createElement('div')) 16 document.body.appendChild(instance.$el) 17 18 // 通過Vue的原型注冊一個方法 19 // 讓所有實例共享這個方法 20 Vue.prototype.$error = (msg) => { 21 instance.msg = msg; 22 instance.show = true; 23 } 24 //隱藏並重置插件 25 Vue.prototype.$errorHide = () => { 26 instance.show = false; 27 instance.msg = ''; 28 } 29 } 30 31 export default error
頁面引用:
beforeDestroy(){ //關閉並重置錯誤展示插件 this.$errorHide() }, created() { //必要參數缺失,則展示錯誤頁面 if(!this.$route.params.coupon_id) { this.$error('當前訪問錯誤,請稍后重試','55%')//根據需要傳入錯誤提示信息 } ......
如上,如果是一般的異常,直接使用默認錯誤提示即可,無需傳參。如需要自定義錯誤信息及寬度,傳入相應參數即可。
另外,由於是全局注入的插件,需要在當前頁面銷毀的時候進行關閉。
