拆分组件的文件(使用打字稿)
Splitting component's files (with typescript)
我们的团队正在为前端部分开始一个基于 Vue 3 的新项目。
我们决定使用 TypeScript 并希望使用文件分离方法。
我们在文档中发现 this article 显示了实现此目的的示例。不幸的是,这个例子没有展示如何使用 TypeScript 实现这一点。
我们尝试过这种方式
/components
┗ /SideBarBtn
┣ sidebar-btn.scss
┣ sidebar-btn.ts
┗ sidebar-btn.vue
边栏-btn.vue
<template>
<h1 class="test">This is a test</h1>
</template>
<script lang="ts" src="./sidebar-btn.ts"></script>
<style lang="scss" src="./sidebar-btn.scss"></style>
边栏-btn.scss
.test {
color: blue;
}
边栏-btn.ts
import { defineComponent } from "vue";
export default defineComponent({
name: "SideBarBtn",
});
Home.vue
<template>
<div class="home">
<img alt="Vue logo" src="../assets/logo.png" />
<SideBarBtn />
</div>
</template>
命令 npm run serve
确实正确执行并加载了页面。但是该组件不可见,并且在控制台中打印警告 Component is missing template or render function.
我们该如何解决这个问题?
问题出在 Home.vue
的 <script>
标签中。 SideBarBtn 是使用别名方法导入的 @/... 并且在 atm 上不起作用。
Home.vue
<script lang="ts">
import { defineComponent } from "vue";
import SideBarBtn from "../components/SideBarBtn/sidebar-btn.vue"; // The name of the vue file has to be complete, with .vue extension
export default defineComponent({
name: "Home",
components: {
SideBarBtn
}
});
</script>
我们的团队正在为前端部分开始一个基于 Vue 3 的新项目。
我们决定使用 TypeScript 并希望使用文件分离方法。 我们在文档中发现 this article 显示了实现此目的的示例。不幸的是,这个例子没有展示如何使用 TypeScript 实现这一点。
我们尝试过这种方式
/components
┗ /SideBarBtn
┣ sidebar-btn.scss
┣ sidebar-btn.ts
┗ sidebar-btn.vue
边栏-btn.vue
<template>
<h1 class="test">This is a test</h1>
</template>
<script lang="ts" src="./sidebar-btn.ts"></script>
<style lang="scss" src="./sidebar-btn.scss"></style>
边栏-btn.scss
.test {
color: blue;
}
边栏-btn.ts
import { defineComponent } from "vue";
export default defineComponent({
name: "SideBarBtn",
});
Home.vue
<template>
<div class="home">
<img alt="Vue logo" src="../assets/logo.png" />
<SideBarBtn />
</div>
</template>
命令 npm run serve
确实正确执行并加载了页面。但是该组件不可见,并且在控制台中打印警告 Component is missing template or render function.
我们该如何解决这个问题?
问题出在 Home.vue
的 <script>
标签中。 SideBarBtn 是使用别名方法导入的 @/... 并且在 atm 上不起作用。
Home.vue
<script lang="ts">
import { defineComponent } from "vue";
import SideBarBtn from "../components/SideBarBtn/sidebar-btn.vue"; // The name of the vue file has to be complete, with .vue extension
export default defineComponent({
name: "Home",
components: {
SideBarBtn
}
});
</script>