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

如何在Vue3项目中使用Vue2开发的WebComponent的插槽?

问题根因

  • Vue3的v-slot/#插槽语法仅适用于Vue组件,不会给原生WebComponent生成标准的slot属性
  • 你遇到的slot属性废弃报错是Vue的ESLint规则,仅针对Vue组件,对WebComponent的标准slot属性不适用
  • 如果未配置Vue将对应标签识别为自定义元素,Vue会尝试将其作为Vue组件解析,导致插槽逻辑异常

解决步骤

步骤1:配置Vue识别自定义元素

根据你使用的构建工具添加配置,避免Vue将WebComponent当成Vue组件处理:

Vite 配置(vite.config.js)
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [
    vue({
      template: {
        compilerOptions: {
          // 匹配你的WebComponent标签前缀,全部识别为原生自定义元素
          isCustomElement: tag => tag.startsWith('my-')
        }
      }
    })
  ]
})
Vue CLI 配置(vue.config.js)
module.exports = {
  chainWebpack: config => {
    config.module
      .rule('vue')
      .use('vue-loader')
      .tap(options => {
        options.compilerOptions = {
          ...(options.compilerOptions || {}),
          isCustomElement: tag => tag.startsWith('my-')
        }
        return options
      })
  }
}

步骤2:关闭对应ESLint规则校验

两种方式按需选择:

  1. 局部单行关闭:在使用slot属性的代码行上方加注释关闭规则
<my-webcomponent-with-two-slots>
  <!-- eslint-disable-next-line vue/no-deprecated-slot-attribute -->
  <div slot="main">
    <div>Hello World</div>
  </div>
  <!-- eslint-disable-next-line vue/no-deprecated-slot-attribute -->
  <div slot="sidebar">
    <div>Hello World</div>
  </div>
</my-webcomponent-with-two-slots>
  1. 全局关闭针对自定义元素的规则:在ESLint配置文件(.eslintrc.js等)中添加规则配置
module.exports = {
  rules: {
    'vue/no-deprecated-slot-attribute': ['error', {
      ignore: ['my-webcomponent-with-two-slots'] // 填入你的WebComponent标签名
    }]
  }
}

完成以上两步即可正常使用插槽,效果和Vue2项目中完全一致。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 19:24:02