Vue 3 基础笔记 6 | 青训营笔记

61 阅读1分钟

这是我参与「第五届青训营」伴学笔记创作活动的第 16 天,今天在开发青训营大项目的过程中,继续学习了如何从头开发一个 Vue 3 的项目,包括 Vue 3 的基础语法等。

组件基础

Vue 使用组件将页面中的元素划分为独立的、可重用的部分。

定义组件

使用单文件组件 (SFC):在 .vue 文件中定义 <script>, <template><style> 标签。

使用 JavaScript 对象:在 .js 文件中默认导出一个 Vue 配置对象,将模板写在 template 配置项中。

import { ref } from 'vue'

export default {
  setup() {
    const count = ref(0)
    return { count }
  },
  template: `
    <button @click="count++">
      You clicked me {{ count }} times.
    </button>`
  // 或者 `template: '#my-template-element'`
}

全局注册组件

使用 Vue 应用实例的 app.component() 方法全局注册组件。

import MyComponent from './App.vue'

app.component('MyComponent', MyComponent)

局部注册组件

使用组合式 API <script setup> 导入后直接在模板中使用。使用选项式 API 需要在 components 选项上注册组件才能使用。

import ButtonCounter from './ButtonCounter.vue'

使用组件

在模板中通过组件名使用组件。

<ButtonCounter />

组件 Props

<script setup> 中使用 defineProps 宏定义 props,宏不需要引入。defineProps 函数传入一个数组,每个元素是一个字符串,表示 prop 的名称。

<script setup>
const props = defineProps(['title'])
</script>

defineProps 函数还可以传入一个对象,对于每个键值对,key 是 prop 的名称,而值则是该 prop 预期类型的构造函数。

const props = defineProps({
  title: String,
  likes: Number
})

在模板中直接通过 props 名(比如 title)访问 props。

script 中使用一个变量 props 接收 defineProps 函数的返回值,然后通过变量 props 访问 props。

组件事件

抛出事件

在模板中子组件可以通过调用内置的 $emit 方法,通过传入事件名称来抛出一个事件:

<template>
  <div class="blog-post">
    <h4>{{ title }}</h4>
    <button @click="$emit('enlarge-text')">Enlarge text</button>
  </div>
</template>

<script setup> 中,需要使用 defineEmits 宏先定义事件:

const emit = defineEmits(['enlarge-text'])

然后使用 defineEmits 的返回值抛出事件。

emit('enlarge-text')

接收事件

在模板中,父组件调用子组件时,通过 @ 加上事件名来定义事件触发时的回调函数。

<BlogPost
  ...
  @enlarge-text="postFontSize += 0.1"
 />

组件插槽

在子组件组件模板中通过 <slot> 元素来定义插槽。父组件传递进来的内容就会渲染在插槽的位置。

在父组件调用子组件时,被组件标签包裹的内容会显示在子组件的插槽中。

动态组件

使用 <component> 标签定义动态组件。

<component> 标签接收一个 is 属性,可以是组件名(需要已注册),或者组件对象(需要已导入)。

<component :is="tabs[currentTab]"></component>