Skip to content

嵌入视频播放器

受到官方文档关于如何搭建团队页面的教程启发,自己捣鼓了一个BiliVideo插件用来在网页上播放来自B站的视频。

创建插件

1.新建文件夹

/theme下新建文件夹/components,并在该文件夹内新建BiliVideo.vue.

如果用Vscode编辑的话建议安装一下vue插件。

2.编辑插件内容

BiliVideo.vue中输入下面的代码:

js
<template>
  <!-- SSR 下先不渲染,避免 hydration 报错 -->
  <ClientOnly>
    <iframe
      :src="iframeSrc"
      scrolling="no"
      frameborder="no"
      allowfullscreen="true"
      style="width:100%;aspect-ratio:16/9;border-radius:6px"
    />
  </ClientOnly>
</template>

<script setup>
import { computed } from 'vue'

const props = defineProps({
  // 支持两种写法:
  // 1) 完整的视频分享链接
  // 2) 直接输入BV号
  bvid: { type: String, required: true }
})

const iframeSrc = computed(() => {
  // 提取纯 BV 号
  const bv = props.bvid.match(/(BV[a-zA-Z0-9]+)/)?.[1]
  if (!bv) throw new Error('BiliVideo 需提供有效 BV 号')
  // 官方 iframe 模板,参数固定
  return `//player.bilibili.com/player.html?isOutside=true&bvid=${bv}&p=1`
})
</script>

注册插件

/theme/index.js中注册插件

js
// https://vitepress.dev/guide/custom-theme
import { h } from 'vue'
import DefaultTheme from 'vitepress/theme'
import './style.css'
import BiliVideo from './components/BiliVideo.vue'
//注意第四个import,注册BiliVideo插件
js
  enhanceApp({ app, router, siteData }) {
    app.component('BiliVideo', BiliVideo)
    //注册BiliVideo插件
  }

使用插件

在任意.md文件中插入即可。

js
<BiliVideo bvid="视频链接或BV号" />

BiliVideo插件实例