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

迁移至Vite后<router-view>使用v-slot报错的解决办法咨询

解决Vite中<router-view>使用v-slot报错:v-slot can only be used on components or <template> tags

问题场景

原代码在Vue编译器下可正常编译,但迁移到Vite后触发报错:

[plugin:vite:vue] v-slot can only be used on components or <template> tags.

涉及代码:

<router-view v-slot="{ Component }">
  <component
    :is="Component"
    class="container"
    ref="componentRef"
  />
</router-view>

解决办法

1. 确保Vue与Vue Router版本匹配

Vue 3必须搭配Vue Router 4.x,Vue 2搭配Vue Router 3.x。版本不匹配会导致组件识别异常,执行对应命令安装适配版本:

# Vue 3 + Router 4
npm install vue-router@4

# Vue 2 + Router 3
npm install vue-router@3

2. 显式导入并局部注册RouterView组件

Vite的Vue插件默认开启更严格的模板检查,全局注册的<router-view>可能被误判为原生标签。改为局部注册即可解决:

<script setup>
import { RouterView } from 'vue-router'
</script>

<template>
  <RouterView v-slot="{ Component }">
    <component
      :is="Component"
      class="container"
      ref="componentRef"
    />
  </RouterView>
</template>

注意使用大写开头的RouterView,对应局部注册的组件名称。

3. 调整Vite的Vue模板编译配置(临时兼容方案,不推荐)

如果不想修改组件代码,可在vite.config.js中关闭模板编译的严格模式:

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [
    vue({
      template: {
        compilerOptions: {
          strict: false
        }
      }
    })
  ]
})

此方法会降低模板检查严格性,可能隐藏其他潜在问题,建议优先使用前两种方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 10:02:13