uniapp vue3版本
背景 原本为app,后期要求h5版本,主要针对与手机钉钉环境使用
下图为企业微信双重导航条效果(钉钉有同样问题,忘了截图,目前只针对钉钉做了处理,思路一致)
最初思路想到了判断运行环境,使用条件编译
实际修改中发现无法判断钉钉微H5应用环境,只能判断出Android与ios,app与h5区别
总之条件编译处理不太理想
app与h5条件处理会导致不自带顶部导航的浏览器效果较差
最终实现
使用钉钉JSAPI
https://open.dingtalk.com/document/orgapp-client/read-before-development
1.设置全局变量判断钉钉环境
import {
getCurrentInstance
} from 'vue'
import * as dd from 'dingtalk-jsapi';
export default {
onLaunch: function() {
const {
appContext
} = getCurrentInstance()
if (dd.env.platform !== "notInDingTalk") {
//在钉钉环境
appContext.config.globalProperties.dingding = true
}else {
appContext.config.globalProperties.dingding = false
}
}
}
2.修改cu-custom组件
colorui/cu-custom.vue
<view>
<view class="cu-custom" v-if="!dingding" :style="[{height:CustomBar + 'px'}]">
<view class="cu-bar fixed" :style="style" :class="[bgImage!=''?'none-bg text-white bg-img':'',bgColor]">
<view class="action" @tap="BackPage" v-if="isBack">
<text class="cuIcon-back"></text>
<slot name="backText"></slot>
</view>
<view class="content" :style="[{top:StatusBar + 'px'}]">
<slot name="content"></slot>
</view>
<view class="right">
<slot name="right"></slot>
</view>
</view>
</view>
</view>
主要加了 v-if="!dingding"
,上一步设置全局变量
加了个插槽,用于搜索按钮,按需用
之前写的uniapp vue3引用colorui cu-custom
<script setup>
部分仅放钉钉JSAPI相关内容
<script setup>
import * as dd from 'dingtalk-jsapi';
import {
useSlots
} from 'vue'
import {
onLoad,
onShow
} from "@dcloudio/uni-app"
// 定义emit search
const emit = defineEmits(['search'])
const slots = useSlots()
onShow(() => {
// 获取content插槽中的标题
const title = slots.content()[0].children
// 这里简单判断是否有right插槽 本项目中仅有搜索一个功能,按需扩展
const right = slots.right?.()
// 判断是否钉钉环境
if (dd.env.platform !== "notInDingTalk") {
// 钉钉JSAPI需在dd.ready中调用
dd.ready(function() {
// dd.ready参数为回调函数,在环境准备就绪时触发,jsapi的调用需要保证在该回调函数触发后调用,否则无效。
// 设置顶部标题
dd.biz.navigation.setTitle({
title: title
});
// 简单判断右插槽存在
if(right) {
// 此为设置右侧多个按钮
dd.biz.navigation.setMenu({
// 多个按钮会有下拉菜单,此为下拉菜单设置
backgroundColor: "#666666",
textColor: "#666666",
// 按钮数组
items: [{
"id": "1", //字符串
"iconId": "search", //字符串,图标命名
"text": "搜索",
// 图标颜色
"iconColor": "#666666"
}],
// 成功回调
onSuccess: function(res) {
// 触发搜索事件
emit('search')
},
onFail: function(err) {
}
});
}
});
}
});
</script>
使用
<cu-custom @search="search()" class="top-bar" isBack="true">
<block #content>这里是标题</block>
<block #right>
<view @click="search">
<image class="search" src="/static/asset/search.png" alt="" />
</view>
</block>
</cu-custom>
@search="search()"
监听组件内触发的emit,进而调用原搜索方法
最终效果
钉钉JSAPI文档不太清晰
需要注意的问题
钉钉JSAPI存在兼容问题,即无法兼容小程序和app,可以条件条件编译优化一下
参考博客
如有问题请讨论