vue组件基础

定义一个组件

当使用构建步骤时,我们一般会将 Vue 组件定义在一个单独的 .vue 文件中,这被叫做单文件组件 (简称 SFC):

1
2
3
4
5
6
7
8
9
<script setup>
import { ref } from 'vue'

const count = ref(0)
</script>

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

组件的使用

要使用一个子组件,我们需要在父组件中导入它。假设我们把计数器组件放在了一个叫做 ButtonCounter.vue 的文件中,这个组件将会以默认导出的形式被暴露给外部ButtonCounter.vue编写如下:

1
2
3
4
5
6
7
8
9
<script setup>
import { ref } from 'vue'

const count = ref(0)
</script>

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

组件的注册

一个 Vue 组件在使用前需要先被“注册”,这样 Vue 才能在渲染模板时找到其对应的实现。组件注册有两种方式:全局注册和局部注册。

全局注册

我们可以使用 Vue 应用实例app.component() 方法,让组件在当前 Vue 应用中全局可用。

1
2
3
4
5
6
7
8
9
10
11
import { createApp } from 'vue'
const app = createApp({})

app.component(
// 注册的名字
'MyComponent',
// 组件的实现
{
/* ... */
}
)

如果使用单文件组件,你可以注册被导入的 .vue 文件;且app.component() 方法可以被链式调用:

1
2
3
4
app
.component('ComponentA', ComponentA)
.component('ComponentB', ComponentB)
.component('ComponentC', ComponentC)

局部注册

本人所有项目编写全部使用局部注册方法。

父子传参Props

Props 声明

一个组件需要显式声明它所接受的 props,这样 Vue 才能知道外部传入的哪些是 props,哪些是透传 attribute。

在使用 <script setup> 的单文件组件中,props 可以在子组件中使用 defineProps() 宏来声明:

1
2
3
4
5
<script setup>
const props = defineProps(['foo'])

console.log(props.foo)
</script>

除了使用字符串数组来声明 prop 外,还可以使用对象的形式,也非常建议使用对象格式,因为Ts只支持这种形式

1
2
3
4
5
// 使用 <script setup>
defineProps({
title: String,
likes: Number
})

父子组件的值通过v-bind自定义方法进行传值操作:

1
2
3
4
5
6
7
8
9
10
11
<template>
<div>
<ButtonCounter :message="message"></ButtonCounter>
</div>
</template>

<script setup>
import { ref } from 'vue';
import ButtonCounter from './components/ButtonCounter.vue';
const message=ref("123")
</script>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<template>
<div>{{message}}</div>
</template>

<script setup>
import {ref} from 'vue'
const count=ref(0);//定义count为一个值0
defineProps({
message:String
})
function addTime(){
count=count++;
return count;
}
</script>

组件的事件

触发事件与监听事件

在组件的模板表达式中,可以直接使用 $emit 方法触发自定义事件 (例如:在 v-on 的处理函数中):

1
2
<!-- MyComponent -->
<button @click="$emit('someEvent')">click me</button>

父组件可以通过 v-on (缩写为 @) 来监听事件,同样,组件的事件监听器也支持 .once 修饰符:

1
<MyComponent @some-event="callback" />

插槽 Slots

插槽内容与出口

<slot> 元素是一个插槽出口 (slot outlet),标示了父元素提供的插槽内容 (slot content) 将在哪里被渲染。

插槽图示

插槽内容可以是任意合法的模板内容,不局限于文本。例如我们可以传入多个元素,甚至是组件。