定义一个组件
使用构建步骤
将 Vue 组件定义在一个单独的 .vue 文件中,这被叫做单文件组件 (简称 SFC)
示例:
<script setup>
import { ref } from 'vue'
const count = ref(0)
</script>
<template>
<button @click="count ">You clicked me {{ count }} times.</button>
</template>
不使用构建步骤
一个 Vue 组件以一个包含 Vue 特定选项的 JavaScript 对象来定义。
import { ref } from 'vue'
export default {
setup() {
const count = ref(0)
return { count }
},
template: `
<button @click="count ">
You clicked me {{ count }} times.
</button>`
// 也可以针对一个 DOM 内联模板:
// template: '#my-template-element'
}
使用组件
script setup 使用组件
导入的组件都在模板中直接可用。
setup函数 使用组件
子个组件将会以默认形式导出暴露给外部,父组件引入,然后注册才可以使用。
传递 props
script setup 传递 props
示例:
<!-- BlogPost.vue -->
<script setup>
defineProps(['title'])
</script>
<template>
<h4>{{ title }}</h4>
</template>
setup 函数传递 props
props 必须以 props 选项的方式声明,props 对象会作为 setup() 函数的第一个参数被传入。
示例:
export default {
props: ['title'],
setup(props) {
console.log(props.title)
}
}
一个组件可以有任意多的 props,默认情况下,所有 prop 都接受任意类型的值。
监听事件
父组件可以通过 v-on 或 @ 来选择性地监听子组件上抛的事件。
示例:
<BlogPost
...
@enlarge-text="postFontSize = 0.1"
/>
子组件可以通过调用内置的 $emit 方法,通过传入事件名称来抛出一个事件。
示例:
<template>
<div class="blog-post">
<h4>{{ title }}</h4>
<button @click="$emit('enlarge-text')">Enlarge text</button>
</div>
</template>
script setup 使用 defineEmits 来声明需要抛出的事件。它返回一个等同于 $emit 方法的 emit 函数。
示例:
<script setup>
defineProps(['title'])
defineEmits(['enlarge-text'])
</script>
setup函数 通过 emits 选项定义组件会抛出的事件。从 setup 上下文对象上访问到 emit 函数(setup() 函数的第二个参数)。
示例:
export default {
emits: ['enlarge-text'],
setup(props, ctx) {
ctx.emit('enlarge-text')
}
}
通过插槽来分配内容
通过 Vue 的自定义
示例:
<template>
<div class="alert-box">
<strong>This is an Error for Demo Purposes</strong>
<slot />
</div>
</template>
<style scoped>
.alert-box {
/* ... */
}
</style>
动态组件
通过 Vue 的
示例:
<!-- currentTab 改变时组件也改变 -->
<component :is="tabs[currentTab]"></component>
:is 的值有被注册的组件名和导入的组件对象