Vue3 组件注册
Vue3 组件注册
- 1. 组件结构
- 1.1 setup
- 1.2 scoped
- 2. 组件注册
- 2.1 全局注册
- 2.2 局部注册
- 2.3 全局注册和局部注册的对比(优先局部注册)
- 3. 组件命名格式(推荐使用大驼峰)
1. 组件结构
当使用构建步骤时,我们一般会将 Vue 组件定义在一个单独的 .vue 文件中,这被叫做单文件组件 (简称 SFC):
<template><button @click="count++">Count is: {{ count }}</button>
</template><script setup>
import { ref } from 'vue'
const count = ref(0)
</script><style scoped>
button{padding: 15px;
}
</style>
1.1 setup
在 Vue3 初期,需要返回一个对象,该对象中包含模板中要用到的数据状态以及方法。
<template><button @click="count++">Count is: {{ count }}</button>
</template><script>
import { ref } from 'vue'
export default {setup() {// 在这里面定数据和方法const count = ref(0)function add() {count.value++}return {count,add}}
}
</script><style lang="scss" scoped></style>
从 Vue3.2 版本开始,推出了 setup 标签,所有定义的数据状态以及方法都会自动暴露给模板使用,从而减少了样板代码。
另外 setup 标签语法还有一些其他的好处:
- 有更好的类型推断
- 支持顶级 await
1.2 scoped
在 定义组件的样式时,在css部分,我们通常会默认加上 scoped ,确保内部的样式只对当前组件有效,否则就会造成样式污染,称为全局样式。造成其他组件的样式问题并且难以排查。
<style scoped>
</style>
2. 组件注册
2.1 全局注册
比如我们现在创建了一个组件 TestComponent.vue
<template><div>这是一个全局测试组件</div></template><script setup></script><style scoped></style>
现在想要进行全局注册,可以在main.js 中加入如下代码:
import testComponent from '@/components/testComponent.vue'app.component('TestComponent', testComponent)
如此,你就可以在项目中的任意组件中无需 import,即可进行使用。比如App.vue:
<template><div><TestComponent></TestComponent></div>
</template><script setup></script><style lang="scss" scoped></style>

另外,app.component 支持链式调用,比如:
app.component('ComponentA', ComponentA).component('ComponentB', ComponentB).component('ComponentC', ComponentC)
2.2 局部注册
局部注册,就是直接在要使用的组件中引入需要的组件,即可进行使用,比如:
<template><div><MyComponent></MyComponent></div>
</template><script setup>
import MyComponent from '@/components/MyComponent.vue';
</script><style lang="scss" scoped></style>
如果没有使用 <script setup>,那就需要选项式语法进行注册。比如:
<template><div><MyComponent></MyComponent></div>
</template><script>
import MyComponent from '@/components/MyComponent.vue';
export default{components: {MyComponent}
}
</script><style lang="scss" scoped></style>
2.3 全局注册和局部注册的对比(优先局部注册)
(1)全局组件虽然方便,但是即使没有使用,也不会tree-shaking;
(2)局部组件的子组件使用,需要明确的导入。而全局组件没有,因此在大型项目中的依赖并没有局部组件明确,这容易影响大型项目组件的稳定性维护。
因此,实际开发时,除了外部引入的组件库。自己项目中写的组件,建议还是使用局部注册
3. 组件命名格式(推荐使用大驼峰)
推荐使用 大驼峰(PascalCase)命名格式,主要原因:
(1)PascalCase 是合法的 JavaScript 标识符,使得导入和注册都很容易;
(2)区别于原生的 html 元素 或者 自定义元素 (web components) 。
在单文件组件和内联字符串模板中,我们都推荐这样做。但是,PascalCase 的标签名在 DOM 内模板中是不可用的。
为了方便,Vue 支持将模板中使用 kebab-case 的标签解析为使PascalCase 注册的组件。这意味着一个以
MyComponent为名注册的组件,在模板 (或由 Vue 渲染的 HTML 元素) 中可以通过<MyComponent>或<my-component>引用。这让我们能够使用同样的 JavaScript 组件注册代码来配合不同来源的模板。
上一章 《Vue3 生命周期》
