在Inertia/Vue组件中使用script标签渲染Schema数据报错求助
解决Vue/Inertia组件SSR渲染Schema数据的报错问题
问题原因
你遇到的[plugin:vite:vue] Tags with side effect (<script> and <style>) are ignored in client component templates错误,是因为Vue客户端组件模板不允许直接放置带有副作用的<script>标签(组件自身的<script>块除外),Vite插件会自动忽略这类标签,导致Schema数据无法正常渲染。
解决方案
方案1:使用Inertia的<Head>组件(推荐)
Inertia提供的<Head>组件专门用于管理页面头部内容,支持添加meta、title和script标签,不会触发Vite的检查机制。
示例代码:
<template> <Head> <title>{{ post.title }} - {{ appName }}</title> <meta name="og:title" :content="post.title" /> <meta name="og:description" :content="post.featured_content" /> <meta name="description" :content="post.featured_content" /> <meta property="og:image" :content="`${appUrl}/storage/${post.banner}`" /> <!-- 渲染Schema数据 --> <script type="application/ld+json" v-html="post.schema_data" /> </Head> <!-- 组件其他内容 --> </template> <script setup> import { Head } from '@inertiajs/vue3'; // 导入其他依赖或定义组件逻辑 </script>
方案2:使用Vue的<Teleport>组件
通过Teleport将Schema脚本直接挂载到页面的<head>标签中,绕过Vite的模板检查:
示例代码:
<template> <Teleport to="head"> <script type="application/ld+json" v-html="post.schema_data" /> </Teleport> <!-- 头部meta标签和组件其他内容 --> <title>{{ post.title }} - {{ appName }}</title> <meta name="og:title" :content="post.title" /> <meta name="og:description" :content="post.featured_content" /> <meta name="description" :content="post.featured_content" /> <meta property="og:image" :content="`${appUrl}/storage/${post.banner}`" /> </template> <script setup> import { Teleport } from 'vue'; // 导入其他依赖或定义组件逻辑 </script>
注意事项
- 确保
post.schema_data是已序列化的合法JSON字符串,如果后端返回的是JSON对象,需要在组件中用JSON.stringify(post.schema_data)转换(注意处理循环引用问题)。 - 不要在组件模板的根级别直接放置
<script>标签,必须通过上述两种方式包裹。
内容的提问来源于stack exchange,提问作者hashan_m
相关产品推荐
相关产品推荐

