需求:在請求封裝里 根據請求返回的狀態 提示不同的彈窗
這樣所有操作請求都會有提示 如果不需要提示的 可以在api接口地址進行配置 ,很好的和用戶交互 並且可以任意調用
第一步創建文件路徑如下結構(下面創建兩個文件都放這里)
第二步 創建組件index.vue
注意:這里使用到uview-ui組件里的u-toast(消息提示)組件為例進行了二次封裝
<template> <view> <u-toast ref="uToast" /> </view> </template> <script> export default { props: { title: { //顯示的文本 type: String, default: '消息' }, type: { // 主題類型,不填默認為 // default-灰黑色 ,error-紅色 代表錯誤 ,primary-藍色 uView的主色調 // success-綠色 代表成功 , // warning-黃色 代表警告 ,info-灰色 比default淺一點 type: String, default: 'success' }, duration:{ //toast的持續時間,單位ms type:Number, default: 2000 }, position:{ //toast出現的位置 type: String, default:"center" }, back:{ // toast結束后,是否返回上一頁,優先級低於url參數 type:Boolean, default:false }, icon:{ // 是否顯示顯示type對應的圖標,為false不顯示圖標 type:Boolean, default:true }, callback:Function ,//回調函數 url:String// 彈窗時間結束后跳轉到指定頁面 }, mounted() { let that = this this.$nextTick(() => { this.$refs.uToast.show({ title: that.title, type: that.type, duration: that.duration, back:that.back, position:that.position, icon:that.icon, url:that.url, callback:that.callback }) // x秒后刪除dom節點 setTimeout(() => { this.$destroy(); document.body.removeChild(this.$el); }, that.duration); }) } } </script> <style scoped> </style>
第三步 創建index.js
import fullNameVue from './index.vue' const FullToast = {}; FullToast.install = function (Vue, option) { const FullNameInstance = Vue.extend(fullNameVue); let name; const initInstance = () => { name = new FullNameInstance(); let nameSpan = name.$mount().$el; document.body.appendChild(nameSpan); } Vue.prototype.$uToast = { showToast(option){ initInstance(); if(typeof option === 'string'){ name.firstName = option; }else if(typeof option === 'object'){ Object.assign(name, option); } return initInstance; } }; } export default FullToast;
第四步 在main.js 進行注冊
import uToast from './components/uToast/index'
Vue.use(uToast);
第五步 完成后訪問方式
1.普通頁面訪問
2.js文件中訪問調用(這里是小馬哥在uni-app的請求進行二次封裝js里調用)
最后調用的效果圖
我是馬丁的車夫,歡迎轉發收藏!