Skip to content

安装插件

此插件为 medium-zoom, 作者为francoischalifour

sh
npm install medium-zoom
sh
yarn add medium-zoom
sh
pnpm add medium-zoom

在vue中使用

更多用法请查看作者GitHub官网, 我这里只展示基本使用

需要的文件目录结构如下:

├─ docs
│  ├─ .vitepress
│  │  └─ config.ts
|  |  ├─ theme
|  |  |  └─ index.ts  # 主题入口, 一定要是index.ts, 不可以是其他名字
|  |  |  └─ custom.css # 自定义样式, 可以是任何名字例如:index.css
|  |  |  └─ Layout.vue # 布局文件, 可以是任何名字, 但还是建议叫Layout.vue

提示

如果某个文件没有, 需要自行创建, 具体的可以参考vitepress官网自定义主题


  1. index.ts中添加如下代码:
index.ts
ts
// .vitepress/theme/index.ts
import { type Theme } from 'vitepress'
import DefaultTheme from 'vitepress/theme'
import './custom.css'
import Layout from './Layout.vue'

export default {
  extends: DefaultTheme,
  Layout,
} satisfies Theme

  1. Layout.vue中添加如下代码:
Layout.vue
vue
<!-- .vitepress/theme/Layout.vue -->
<template>
    <!-- 这里的Layout不是递归组件, 而是默认主题的Layout组件, 相当于组件的入口, 若不使用此组件, 那么整个网页都没有内容 -->
  <Layout></Layout>
</template>

<script type="ts" setup>
import DefaultTheme from 'vitepress/theme'
import mediumZoom from 'medium-zoom'
import { watch, nextTick, onMounted } from "vue";
const { Layout } = DefaultTheme
import { useRouter } from "vitepress";
let { route } = useRouter(); // 页面路由对象

const initZoom = () => {
  mediumZoom('img', { background: 'var(--vp-c-bg)' });
}
onMounted(() => {

  initZoom();

  // 监听路由变化
  watch(() => route.path, () => {
    nextTick(() => {
      initZoom();
    });
  }
  );
});
</script>

  1. 添加自定义样式

作者GitHub官网中说到, 此插件默认是没有提供z-index值, 但作者给了一个解决方案, 可以在自定义样式中添加如下样式

custom.css
css
.medium-zoom-overlay,
.medium-zoom-image--opened {
  z-index: 999;
}

提示

最终效果参考此文档

Released under the MIT License.