Vue3$Component-Introduce

65 阅读1分钟

Vue3$Component-Introduce

1. What is Component 组件是什么

Component 组件:功能的封装。组件封装了HTML,JavaScript 及 CSS。

Vue的单文件组件 SFC (Single File Component)是 以.vue结尾的文件。组成部分:

  • script标签是加强版的 script:可以使用宏函数
  • template标签是加强版的 HTML:定义了一些语法便于变量的使用,功能类似 JSX
  • style标签是加强版的 style:scoped只作用于当前组件,lang可以声明使用 less 、sass 等语法,可以通过v-bind()使用变量

2. How to Use Component 组件的使用

1. 定义组件

// @file ButtonCounter.vue
<script setup>
import { ref } from 'vue'
const count = ref(0)
</script>

<template>
  <button @click="count++">You clicked me {{ count }} times.</button>
</template>

2. 注册组件

1. 局部注册

// @file ComponentX.vue
<script setup>
import ComponentA from './ComponentA.vue'
</script>

2. 全局注册

// @file main.js
app
  .component('ComponentA', ComponentA)
  .component('ComponentB', ComponentB)

3. 使用组件

<script setup>
import ButtonCounter from './ButtonCounter.vue'
</script>

<template>
  <h1 class="title">Here is a child component!</h1>
  <ButtonCounter />
</template>

<style scoped lang="scss">
.title {
	color: orange;
}
</style>

动态组件

<component :is="componentName"></component> // or componentObj

Links

VueComponentBasics

VueComponentRegister