在Vue 3中,实现了全屏功能的组件,开箱即用。
注意:iPhone的Safari 不支持js触发全屏功能,所以这里面部分代码有根据条件screenfull.isEnabled
跳过。建议触发全屏的按钮也根据条件screenfull.isEnabled
显隐。
使用了screenfull
依赖库,可以省去浏览器适配的麻烦。
代码如下:
<template>
<div ref="myFullScreen" >
<slot></slot>
</div>
</template>
<script setup lang="ts">
import { ModelRef, ref, watch } from "vue";
import screenfull from "screenfull";
const myFullScreen = ref();
const isFull: ModelRef<boolean> = defineModel<boolean>({ default: false });
// Esc退出 F11 退出等 会触发这个事件,要及时更新最新的状态
// 全屏前后样式上的调整,建议也在这里面填写
if (screenfull.isEnabled) {
screenfull.on("change", () => {
isFull.value = screenfull.isFullscreen;
showFullBackground.value = isFull.value;
});
}
const fullScreenChange = () => {
if (!screenfull.isEnabled) {
return;
}
if (isFull.value) {
screenfull.request(myFullScreen.value);
} else {
screenfull.exit();
}
};
watch(isFull, () => {
fullScreenChange();
});
</script>
这个组件开放了一个v-model给引用的组件,使用方法如下:
<template>
<MyFullScreen v-model="isFull">
...
<el-icon @click="switchFullScreen" ><FullScreen /></el-icon>
</MyFullScreen>
</template>
<script lang="ts" setup>
const isFull: Ref<boolean> = ref(false);
const switchFullScreen = () => {
isFull.value = !isFull.value;
};
</script>
结束。