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

Vue3自定义组件库集成Inertia <Link />组件报错求助

问题解决:自定义Vue3组件库中Inertia Link组件点击报错

核心原因

组件库仅将vue标记为外部依赖,但未处理@inertiajs/vue3,导致组件库打包时嵌入了独立的Inertia模块,与主项目的Inertia上下文冲突;同时封装的Link组件未透传必要props,引发功能异常。

解决方案

1. 调整组件库Vite配置,将Inertia设为外部依赖

修改组件库的vite.config.js,把@inertiajs/vue3加入外部依赖列表,确保组件库复用主项目的Inertia实例:

import { resolve } from "path";
import vue from "@vitejs/plugin-vue";

export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      "@": "/src",
      "@assets": "/src/assets",
    },
  },
  css: {
    postcss: resolve(__dirname, "postcss.config.js"),
  },
  build: {
    lib: {
      entry: resolve(__dirname, "src/index.js"),
      name: "VueInertiaCore",
      fileName: "vue-inertia-core",
    },
    rollupOptions: {
      // 添加@inertiajs/vue3到外部依赖
      external: ["vue", "@inertiajs/vue3"],
      output: {
        globals: {
          vue: "Vue",
          "@inertiajs/vue3": "InertiaVue3",
        },
      },
    },
  },
});

2. 完善组件库Link组件的props透传

修改组件库的Link.vue,透传Inertia Link原生props,保证功能完整:

<script setup>
import { Link } from "@inertiajs/vue3";
// 透传Inertia Link的所有原生props
const props = defineProps({
  ...Link.props,
});
</script>

<template>
    <Link v-bind="props" class="text-sm font-bold leading-tight">
        <slot></slot>
    </Link>
</template>

<style scoped></style>

3. 配置组件库的Peer Dependencies

在组件库package.json中添加peer依赖,确保与主项目的Vue、Inertia版本兼容:

{
  "peerDependencies": {
    "vue": "^3.0.0",
    "@inertiajs/vue3": "^1.0.0"
  }
}

4. 确认主项目Inertia初始化正确

主项目app.js需正确初始化Inertia,保证上下文全局可用:

import { createApp, h } from 'vue'
import { createInertiaApp } from '@inertiajs/vue3'

createInertiaApp({
  resolve: name => require(`./Pages/${name}`),
  setup({ el, App, props, plugin }) {
    createApp({ render: () => h(App, props) })
      .use(plugin)
      .mount(el)
  },
})

完成以上步骤后,重新构建组件库并更新主项目依赖,即可解决Link组件点击报错问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 18:23:10