Vue3入门-04组件基础
组件:组件允许我们将UI划分为独立的、可重用的部分,并且可以对每个部分进行单独的思考。在实际应用中,组件常常被组织成层层嵌套的树状结构。
在vue中组件占据着重要的地位,通过本章节先进行简单的入门,而后再进行细致的讲解。
本章主要包括:组件的定义、组件的使用、组件值的传递、组件事件的监听、插槽的使用、动态组件以及DOM模板解析注意事项。
选项式API
组件的定义
当使用构建步骤是,我们一般会将Vue组件定义在一个单独的.vue文件中,这被叫做单文件组件(Single File Compoent,简称SFC)。
<script>
export default {
data() {
return {
count: 0
}
}
}
</script>
<template>
<button @click="count++">You clicked me {{ count }} times.</button>
</template>
组件的使用
组件可以被多次重用
- 导入外部组件
- 在compoents中注册
- 在template中使用
<script>
import ButtonCounter from './ButtonCounter.vue'
export default {
components: {
ButtonCounter
}
}
</script>
<template>
<h1>Here is a child component!</h1>
<ButtonCounter />
</template>
传递props值
通过props可以将父组件想要传递的值传递过去,父组件将值传递过去后,每一个子组件都会产生一个新的实例,所以每个组件中的值可能会不同。
实现方法:
- 在父组件中使用属性的赋值方式将值赋值给子组件
- 在子组件中定义props来接受参数
- 直接在子组件中使用子组件模板中使用
子组件:
<!-- BlogPost.vue -->
<script>
export default {
props: ['title']
}
</script>
<template>
<h4>{{ title }}</h4>
</template>
父组件
<BlogPost title="My journey with Vue" />
<BlogPost title="Blogging with Vue" />
<BlogPost title="Why Vue is so fun" />
监听事件
通过监听事件,父组件可以获得子组件触发的相应事件并且设置响应方法,比如子组件中如果触发click,父组件就可以捕获到事件并且执行响应方法。
实现步骤:
- 在父组件调用子组件时中设置响应方式
- 子组件中声明emits内容
- 在子组件的响应事件中设置$$emit(‘响应事件’)$
父组件
<template>
<div :style="{ fontSize: postFontSize + 'em' }">
<BlogPost
v-for="post in posts"
:key="post.id"
:title="post.title"
@enlarge-text="postFontSize += 0.1"
></BlogPost>
</div>
</template>
子组件
<script>
export default {
props: ['title'],
emits: ['enlarge-text']
}
</script>
<template>
<div class="blog-post">
<h4>{{ title }}</h4>
<button @click="$emit('enlarge-text')">Enlarge text</button>
</div>
</template>
通过插槽来分配内容
一些情况下我们会希望能和HTML元素一样想组件中传递内容,就可以通过Vue自定义的<slot>
来实现。
实现步骤:
- 在子组件中插入slot
- 在父组件中插入内容
父组件
<AlertBox>
Something bad happened.
</AlertBox>
子组件
<template>
<div class="alert-box">
<strong>This is an Error for Demo Purposes</strong>
<slot />
</div>
</template>
<style scoped>
.alert-box {
/* ... */
}
</style>
动态组件
在有一些场景会需要切换不同的组件,比如tab,可以通过Vue的component
元素和特殊的is
attribute实现。
<!-- currentTab 改变时组件也改变 -->
<component :is="currentTab"></component>
当使用component时切换不同的组件,被切换的组件就会被卸载。
DOM 模板解析注意事项
如果想在DOM中直接书写Vue模板,Vue则必须从DOM中获得字符串。
在DOM中有以下注意事项:
- 区分大小写
- 闭合标签必须和标签头成对出现,如
<my-component></my-component>
- 元素位置:li必须在ul或ol中,tr必须在table中