介绍
uniapp的组件只能通过import引入,每个页面都要用的话,就会重复引入较为麻烦,因此实现一个全局组件非常有用。
实现思路:
创建一个组件页面,将背景颜色设置为透明,当前页通过uni.navigateTo()跳转到透明的全局组件页面,uni.navigateBack(-1)回到当前页.实现全局页面的弹窗。可将该方法注册到全局方法上,通过命令调用该方法,实现代码简化。
一、创建一个组件页面 index.vue
<template>
<up-popup :show="show" round="20" bgColor="#FFE4E5" mode="center" @close="close" class="dialog">
<view class="title">弹窗内容</view>
</up-popup>
</template>
<script setup name="globalPopup">
import {
onLoad,
onUnload
} from '@dcloudio/uni-app'
import {
getCurrentInstance
} from 'vue';
import {
warnType
} from '@/const/index.js'
//获取当前vue的实例
const instance = getCurrentInstance().proxy
let show = ref(false)
const data = ref({})
onLoad(() => {
//页面间事件通信通道
const eventChannel = instance.getOpenerEventChannel()
//持续监听一个事件
eventChannel.on('globalPopup', (item) => {
init(item)
})
})
//初始化弹窗组件
const init = (params) => {
show.value = true
data.value = params
}
//关闭弹窗组件
const close = () => {
show.value = false
uni.navigateBack({
delta: 1
})
}
defineExpose({
init
})
</script>
<style>
/**页面背景必须设置为透明**/
page {
background: transparent;
}
</style>
二、页面注册 pages.json
{
"path": "components/globalPopup/index",
"style": {
"navigationStyle": "custom", //自定义头部
"backgroundColor": "transparent",//背景透明
"app-plus": {
"animationType": "fade-in", //淡入效果
"background": "transparent",//背景透明
"popGesture": "none",
"bounce": "none",
"titleNView": false
}
}
},
三、注册vue的全局方法 globalPopup.js
const install = app => {
app.config.globalProperties.$globalPopup = {
show(params) {
//当前页的路由
let pointPageUrl = getCurrentPages()[getCurrentPages().length - 1].route;
console.log('params', pointPageUrl)
if (pointPageUrl == 'components/globalPopup/index') return
uni.navigateTo({
url: '/components/globalPopup/index',
success: function(res) {
// 利用事件 通知 目标页面
res.eventChannel.emit('globalPopup', params)
}
})
}
}
}
export default install;
四、在main.js中引入全局的方法
import {createSSRApp} from 'vue'
import globalPopupjs from './components/globalPopup/globalPopup.js'
const app = createSSRApp(App)
app.use(globalPopupjs)
五、在业务代码中使用
import { getCurrentInstance } from 'vue';
const {proxy} = getCurrentInstance()
proxy.$globalPopup.show(data)