uniapp结合vue3+ts 微信小程序环境中点击元素使video视频全屏播放,退出全屏后停止播放
这个需求主要是用到uni-app中的createVideoContext这个API这个API需要接收两个参数videoId, componentInstance其中videoId很好理解就是video组件设置的id而componentInstance就不一样了在vue2中可以直接传入thisthis.videoContext uni.createVideoContext(myvideo, this); this.videoContext.requestFullScreen({ direction: 90 }); this.videoContext.play();但是在vue3中是没有this的本来还以为可以不用传第二个参数因为在官方文档中也没有传图uni.createVideoContext(videoId, componentInstance) | uni-app官网后来发现不行可能还是要传一般在vue3中需要获取DOM元素只能先声明变量 利于 const videoRef ref(null) 获取在页面挂载后value就能获取但是我在小程序拿到的都是null传进API也不起作用后来才发现是由于小程序环境的限制不能直接在setup函数内部使用ref来获取DOM元素。解决办法直接将页面实例传入进去const videoRef ref(); const instance getCurrentInstance(); onMounted(() { videoRef.value uni.createVideoContext(myvideo, instance); // 替换为你自己的videoid });之后就可以通过videoRef.value 调用requestFullScreen实现video的全屏显示也能调用播放、暂停等api。完整代码template scroll-view classcase-list scroll-xtrue enable-flextrue :show-scrollbarfalse view classcase-card v-for(item, index) in caseList :keyindex clickshowFullVideo(item) view classcard-top image :srcitem.listImage classimg lazy-load/image /view view classcard-cont view classcase-title{{item.title}}/view view classcase-info{{item.summary}}/view /view /view /scroll-view view v-showvideoUrl classfull-video video idmyVideo refmyVideo :srcvideoUrl autoplay :controlstrue enable-danmutrue fullscreenchangechangeFull/video /view /template script setup import { ref, getCurrentInstance, onMounted } from vue; const props defineProps({ //轮播图列表 caseList: { type: Array, required: true, default: () [] } }) const videoRef ref(); const instance getCurrentInstance(); const videoUrl ref(); const pageScrollTop ref(0); // 点击全屏播放 const showFullVideo (item) { // 获取当前页面滚动距离 uni.createSelectorQuery().selectViewport().scrollOffset(res { pageScrollTop.value res.scrollTop }).exec() videoUrl.value https://wtxwebsite.oss-cn-hangzhou.aliyuncs.com/product/video/1770602075022-WTX-SM筛选机宣传视频.mp4; setTimeout(() { videoRef.value.play(); // videoRef.value.requestFullScreen({ direction: 90 }); videoRef.value.requestFullScreen(); }, 100) } const changeFull (e) { if (!e.detail.fullscreen) { // 退出全屏 videoRef.value.exitFullScreen() videoRef.value.pause() videoUrl.value null; // 回到原来的滚动位置 setTimeout(() { uni.pageScrollTo({ scrollTop: pageScrollTop.value, duration: 0 // 瞬间回去无动画 }) }, 10) } } onMounted(() { videoRef.value uni.createVideoContext(myVideo, instance); }); /script