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

Vue 3如何渲染挂载容器内的原有HTML内容?

Vue 3.3.2 保留挂载容器原有HTML的解决方案

你可以通过预存挂载容器的原有HTML内容,再在组件内渲染的方式实现需求,完全兼容Hugo这类静态站点生成器,具体有两种实现方式:

方式一:在挂载前传递原有内容到组件

修改main.ts,先获取容器的原始HTML,再作为props传给组件:

// main.ts
const container = document.getElementById('paid-content')
const originalContent = container?.innerHTML || ''

createApp(PaidContent, { originalContent }).mount('#paid-content')

然后在PaidContent.vue中接收props并渲染:

<template>
  <div v-if="isLoggedIn">
    <p>You are signed in!</p>
    <!-- 渲染原有HTML内容 -->
    <div v-html="originalContent"></div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'

// 定义接收的props
const props = defineProps<{
  originalContent: string
}>()

// 替换为实际的登录状态判断逻辑
const isLoggedIn = ref(true)
</script>

方式二:组件内部直接获取原有内容

如果不想修改main.ts,可以在组件的beforeMount钩子中获取容器的原始HTML(此时Vue还未替换容器内容):

<template>
  <div v-if="isLoggedIn">
    <p>You are signed in!</p>
    <div v-html="originalContent"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, beforeMount } from 'vue'

const originalContent = ref('')
const isLoggedIn = ref(true)

beforeMount(() => {
  const container = document.getElementById('paid-content')
  if (container) {
    originalContent.value = container.innerHTML
  }
})
</script>

注意事项

  • 使用v-html时要确保原有HTML内容是安全的(无恶意脚本),由于你的内容来自Hugo静态生成,风险极低;
  • 两种方式都能避免Vue默认替换容器内容的行为,同时保留原有<h2>标签和组件自身的登录提示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 02:00:14