Vue3 中使用 VueUse 实现指定区域全屏阅读功能

作者:小布丁时间:2026-10-31 13:55:05浏览:222

本文介绍如何在 Vue3 项目中利用 VueUse 库的 useFullscreen 函数实现指定 DOM 区域的全屏阅读功能。通过安装依赖、引入 Hook 并绑定元素 ref,可轻松获取 isFullscreen 状态及 toggle 切换方法,配合按钮点击事件完成全屏与退出全屏的逻辑控制。

本方案基于 VueUse 库中的 useFullscreen 函数,该库提供了大量封装好的实用函数,能够显著提升开发效率。

具体用法可参考 VueUse 官方文档:

Home | VueUse

实现流程

第一步,需在项目中安装 vueuse 依赖。

npm i @vueuse/core

其次,在需要实现全屏功能的页面组件中引入 useFullscreen。

import { useFullscreen } from '@vueuse/core'

具体使用方式如下(本文示例基于 Vue3):

将需要全屏展示的元素通过 ref 绑定到变量 mainele,并将其作为参数传入 useFullscreen,从而获取全屏相关的数据和方法。

isFullscreen:布尔类型值,用于判断当前是否处于全屏状态。

toggle:调用该函数可实现全屏与非全屏状态的切换。

const mainele = ref<HTMLElement | null>(null);
const isFullscreentext = ref("全屏阅读");
const { isFullscreen, enter, exit, toggle } = useFullscreen(mainele);
const changeFullscreen = () => {
  toggle();
  if (isFullscreen.value) {
    isFullscreentext.value = "全屏阅读";
  } else {
    isFullscreentext.value = "退出全屏";
  }
};

完整代码

<template>
  <div>
    <h1 style="text-align: center;">全屏阅读测试</h1>
    <div ref="mainele">
      <el-button type="primary" @click="changeFullscreen">{{
        isFullscreentext
      }}</el-button>
      <div style="width: 100%; height: 90vh; background-color: antiquewhite">
        内容内容内容内容内容
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref } from "vue";
import { useFullscreen } from "@vueuse/core";
const mainele = ref<HTMLElement | null>(null);
const isFullscreentext = ref("全屏阅读");
const { isFullscreen, enter, exit, toggle } = useFullscreen(mainele);
const changeFullscreen = () => {
  toggle();
  if (isFullscreen.value) {
    isFullscreentext.value = "全屏阅读";
  } else {
    isFullscreentext.value = "退出全屏";
  }
};
</script>

至此,关于在 JS/Vue3 中实现页面指定区域全屏阅读功能的内容介绍完毕,更多相关 js 指定区域全屏阅读内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!

作者最新文章