【发布时间】:2021-02-23 01:57:02
【问题描述】:
我们正在尝试创建一个 Vue npm 包,其中一个组件导入另一个组件(一个简单的示例可能是 - 该包包含一个通用按钮组件和一个使用我的按钮组件进行分页的表格组件)。我可以将子组件导入父组件并成功构建包。但是当我在应用程序中导入和使用父组件(从包中)时,子组件内容不显示。跳过它,就像它不存在一样。
我很茫然。
我正在使用一些非常简单的组件进行测试:
<!-- Child Component -->
<template>
<div id="childElement">Child Component</div>
</template>
<script>
export default {
name: "childComponent"
}
</script>
<style>
#childElement {
font-weight: bold;
}
</style>
<!-- Parent Component -->
<template>
<div>
<div id="parentElement">Parent Component</div>
<child-component></child-component>
</div>
</template>
<script>
import ChildComponent from "./ChildComponent.vue";
export default {
name: "parentComponent",
components: {
ChildComponent
}
}
</script>
<style>
#parentElement {
font-weight: bold;
}
</style>
(编辑)这是我的 index.js 文件
import ParentComponent from './components/ParentComponent.vue';
import ChildComponent from './components/ChildComponent.vue';
const install = Vue => {
Vue.component("ParentComponent", ParentComponent);
Vue.component("ChildComponent", ChildComponent);
};
export default {
install
};
export { ParentComponent, ChildComponent };
用法(在不同的应用程序中,在“添加纱线...”之后)
<template>
<div>
<div>
<h1>Testing Section</h1>
<parent-component></parent-component>
<h1>End Testing Section</h1>
</div>
</div>
</template>
<script>
import { ParentComponent, ChildComponent } from ...;
export default {
name: 'TestApp',
components: {
ParentComponent,
ChildComponent
}
};
</script>
这就是我在页面上看到的:
测试部分 父组件 结束测试部分以下是我知道的一些事情:
- ParentComponent 到 ChildComponent 的导入路径正确。如果我故意将路径更改为不存在的东西,则在尝试构建时会出错。
- 如果我直接在应用程序中导入和使用 ChildElement,它会按预期工作。
- 如果我将 ParentComponent 和 ChildComponent 复制到应用程序结构中,然后以这种方式导入它们(而不是从包中导入它们),那么 ParentComponent 就会完全按照我的预期显示 ChildComponent。
我看到其他似乎以这种方式导入组件的包,所以我认为我正在做的事情是可能的。
如果有人有任何想法,我将不胜感激!
(如果我包含项目中的更多代码,请告诉我是否有帮助)
更新 我已经追踪了更多。当我包含子组件时,我从应用程序收到此警告:
[Vue 警告]:resolveComponent 只能在 render() 或 setup() 中使用。
这帮助我在互联网上找到了其他资源,但没有任何帮助。我的简单测试没有在任何地方明确使用 resolveComponent。如果我确实使用它和一个渲染函数而不是一个模板,同样的结果,同样的警告。
【问题讨论】:
-
我无法重现您给出的示例的问题。但是,问题可能在于您构建库的方式,或者您在应用程序中导入组件的方式。你能在 GitHub 上提供一个 repro 吗?
-
你是否在包中包含了模板编译器?在
vue.config.js中包含runtimeCompiler: true。 -
@Ackroydd 不需要,因为 OP 正在使用 SFC。
-
在 sfc 中有模板...
标签: vue.js vue-component vuejs3 npm-package