You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:Vue3中SSR友好的HTML渲染实现方案

解决Vue3 SSR下API获取HTML内容的SEO问题

你的核心问题是:onMounted是客户端专属钩子,SSR阶段不会执行,导致API获取的内容仅在客户端渲染,无法被搜索引擎爬虫抓取。以下是两种SSR友好的解决方案:

1. Nuxt3 环境(推荐)

Nuxt3内置了服务端数据预取工具,直接使用useFetch或useAsyncData即可在服务端完成API请求,数据会被注入到页面初始源码中:

<template>
  <div v-html="sanitizedText"></div>
</template>

<script setup>
import DOMPurify from 'dompurify'

// 服务端预获取数据,自动处理SSR/客户端数据同步
const { data: rawText } = await useFetch('/api/your-content-api')

// 安全过滤HTML,防止XSS攻击
const sanitizedText = computed(() => {
  if (!rawText.value) return ''
  return DOMPurify.sanitize(rawText.value)
})
</script>

2. 纯Vue3 + Vite SSR 环境

使用Vue官方提供的serverPrefetch钩子,专门用于SSR阶段的组件数据预取:

<template>
  <div v-html="sanitizedText"></div>
</template>

<script setup>
import { ref, computed } from 'vue'
import DOMPurify from 'dompurify'

const rawText = ref('')

// SSR阶段执行:服务端预取数据
serverPrefetch = async () => {
  const res = await fetch('https://your-api-domain/content')
  rawText.value = await res.text()
}

// 客户端兜底:处理客户端导航场景
if (import.meta.client && !rawText.value) {
  (async () => {
    const res = await fetch('https://your-api-domain/content')
    rawText.value = await res.text()
  })()
}

// 安全过滤HTML
const sanitizedText = computed(() => DOMPurify.sanitize(rawText.value))
</script>

关键注意事项

  • 确保服务端能正常访问目标API:内部API可直接调用,外部API需配置服务端代理避免跨域
  • 必须对获取的HTML内容做XSS过滤:DOMPurify是常用的安全处理库,避免恶意脚本注入

内容的提问来源于stack exchange,提问作者DudiDude

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 13:42:40