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

Vue 3服务端渲染style标签引号转HTML实体致样式失效求解决

解决Vue 3 SSR中style标签引号被转义导致样式失效的问题

针对你遇到的Vue 3.2.47版本结合vue/server-renderer渲染时,style标签内引号被转成HTML实体(如')导致样式失效的问题,提供以下几种可行解决方法:

方法一:使用v-html渲染style内容

将模板中的静态style内容改为动态绑定,通过v-html直接插入原始CSS代码,避免转义:

  1. 调整组件代码,将CSS内容存入data:
const app = createApp({
  data: () => ({
    ...testData,
    styleContent: `/* 这里是你的原始CSS代码,包含引号 */
    .example::after {
      content: '测试文本';
      color: red;
    }`
  }),
  template: `<div><!-- 其他模板内容 -->
    <style v-html="styleContent"></style>
  </div>`,
});
  1. 若你的模板是从外部文件读取,可拆分模板结构,将style部分改为动态绑定,或者读取style文件内容存入data后用v-html渲染。

方法二:自定义SSR渲染器跳过style标签内容转义

通过createRenderer创建自定义渲染器,对style标签的文本内容标记为原始内容,跳过转义处理:

import { createApp } from 'vue';
import { createRenderer } from '@vue/server-renderer';
import fs from 'fs';
import path from 'path';

// 创建自定义渲染器
const renderer = createRenderer({
  transformNode(node) {
    // 匹配style标签,处理其子文本内容
    if (node.tag === 'style' && node.children?.[0]?.type === 2 /* TEXT_NODE */) {
      node.children[0].isRaw = true; // 标记为原始内容,禁用转义
    }
    return node;
  }
});

const app = createApp({
  data: () => testData,
  template: fs.readFileSync(path.resolve(__dirname, './../templates/sample.html'), 'utf-8'),
});

// 使用自定义渲染器渲染
const htmlString = await renderer.renderToString(app, context);

方法三:升级Vue到3.3+版本

Vue 3.2.x版本的SSR在处理style标签内的文本转义时存在bug,后续3.3.x版本已修复该问题。直接升级Vue及相关依赖到最新稳定版,即可无需额外处理解决该问题:

npm update vue @vue/server-renderer

补充说明

你尝试的open-quote/no-open-quote等CSS伪元素方法不适用该场景,因为问题根源是HTML转义导致CSS语法被破坏,而非CSS引号的语法使用问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 23:46:00