Storybook中Inertia-Link组件无法正常渲染问题求解
问题背景
在Laravel项目中搭配Inertia使用Storybook时整体体验顺畅,但封装Inertia官方Link组件的导航链接组件出现渲染异常:
- 组件已在Storybook完成注册,但无法正常渲染,排查确认是
inertia-link替换原生HTML标签导致 - 手动在浏览器元素检查中将标签替换为原生
a标签后,组件可正常渲染 - 控制台报错明确指向Inertia-Link组件解析失败,报错信息如下:
[Vue warn]: Failed to resolve component: Link If this is a native custom element, make sure to exclude it from component resolution via compilerOptions.isCustomElement. at <AppNavLink href="/" >
现有代码
导航组件代码(AppNavLink.vue)
<template> <Link class="font-medium uppercase hover:text-blue-600 dark:hover:text-blue-400" :class="{ 'text-blue-500 hover:text-blue-500 dark:hover:text-blue-500': active, }" > <slot /> </Link> </template> <script> export default { props: { active: Boolean, }, } </script>
Storybook配置代码
import NavLink from '../resources/js/components/ui/AppNavLink.vue' import { Link } from '@inertiajs/inertia-vue3' // 默认导出决定story在列表中的位置 export default { title: 'Design System/Navbar link', component: NavLink, subcomponents: { Link }, } // 创建参数与渲染映射的模板 const Template = (args) => ({ components: { NavLink, Link }, setup() { // 参数将传入模板 return { args } }, template: ' <NavLink href=args.href > Posts </NavLink>', }) export const Default = Template.bind({}) Default.args = { href: '/', }
已尝试方案
已在Story配置中引入并注册@inertiajs/inertia-vue3的Link组件,仍然无法解决组件解析报错,需要找到正确的Inertia Link导入配置方式,实现组件在Storybook中的正常渲染。
解决方案
问题根源为仅在单个story的局部注册了Link组件,但AppNavLink.vue内部使用Link时既未做全局注册,也未在组件内部导入Link,同时组件本身存在prop漏声明、属性绑定错误的问题,按以下步骤修复即可:
- 修改
AppNavLink.vue,在组件内部显式导入Link组件(不要依赖全局注册),补全缺失的hrefprop并绑定到Link组件上:
<template> <Link :href="href" class="font-medium uppercase hover:text-blue-600 dark:hover:text-blue-400" :class="{ 'text-blue-500 hover:text-blue-500 dark:hover:text-blue-500': active, }" > <slot /> </Link> </template> <script> import { Link } from '@inertiajs/inertia-vue3' export default { components: { Link }, props: { active: Boolean, href: String }, } </script>
- 修复Story配置里的模板语法错误,原代码中
href=args.href未做响应式属性绑定,修改后的story配置如下:
import NavLink from '../resources/js/components/ui/AppNavLink.vue' export default { title: 'Design System/Navbar link', component: NavLink, } const Template = (args) => ({ components: { NavLink }, setup() { return { args } }, template: '<NavLink v-bind="args">Posts</NavLink>', }) export const Default = Template.bind({}) Default.args = { href: '/', active: false }
- 若仍存在组件解析报错,直接在Storybook的Vue预览配置文件(默认路径为
.storybook/preview.js)中全局注册Link组件即可:
import { app } from '@storybook/vue3' import { Link } from '@inertiajs/inertia-vue3' app.component('Link', Link)
配置完成后重启Storybook即可正常渲染组件。
内容的提问来源于stack exchange,提问作者Emil Beck Aagaard
相关产品推荐
相关产品推荐

