Skip to main content

组件是如何使用的

单文件组件

是一种类似 HTML 格式的文件,也被称为 *.vue 文件。

单文件组件会将一个组件的逻辑 (JavaScript),模板 (HTML) 和样式 (CSS) 封装在同一个文件里。

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

<template>
<button @click="count++">Count is: {{ count }}</button>
</template>

<style scoped>
button {
font-weight: bold;
}
</style>

组件注册

一个 Vue 组件在使用前需要先被注册,这样 Vue 才能在渲染模板时找到其对应的实现。

全局注册

import { createApp } from 'vue'

const app = createApp({})

app
.component('ComponentA', ComponentA)
.component('ComponentB', ComponentB)
.component('ComponentC', ComponentC)
<!-- 这在当前应用的任意组件中都可用 -->
<ComponentA/>
<ComponentB/>
<ComponentC/>

局部注册

局部注册的组件仅在当前组件可用。

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

<template>
<ComponentA />
</template>

Props

props传递

任何类型的值都可以作为 props 的值被传递。

<MyComponent greeting-message="hello" />
<script setup lang="ts">
defineProps<{
greetingMessage: String
}>()
</script>

静态与动态

<!-- 静态props -->
<MyComponent greeting-message="hello" />

<!-- 动态props -->
<MyComponent :greeting-message="data.messgae" />

单向绑定

所有的 props 都遵循着单向绑定原则,props 因父组件的更新而变化,自然地将新的状态向下流往子组件,而不会逆向传递。

每次父组件更新后,所有的子组件中的 props 都会被更新到最新值。

当对象或数组作为 props 被传入时,虽然子组件无法更改 props 绑定,但仍然可以更改对象或数组内部的值。这是因为 JavaScript 的对象和数组是按引用传递。

props校验

可以声明对传入的 props 的校验要求。

defineProps({
// 基础类型检查
// (给出 `null` 和 `undefined` 值则会跳过任何类型检查)
propA: Number,
// 多种可能的类型
propB: [String, Number],
// 必传,且为 String 类型
propC: {
type: String,
required: true
},
// Number 类型的默认值
propD: {
type: Number,
default: 100
},
// 对象类型的默认值
propE: {
type: Object,
// 对象或数组的默认值
// 必须从一个工厂函数返回。
// 该函数接收组件所接收到的原始 prop 作为参数。
default(rawProps) {
return { message: 'hello' }
}
},
// 自定义类型校验函数
propF: {
validator(value) {
// The value must match one of these strings
return ['success', 'warning', 'danger'].includes(value)
}
},
// 函数类型的默认值
propG: {
type: Function,
// 不像对象或数组的默认,这不是一个
// 工厂函数。这会是一个用来作为默认值的函数
default() {
return 'Default function'
}
}
})
type可校验类型
Number
String
Boolean
Symbol
Object
Array
Function
Date
自定义类或构造函数