组件概述
组件允许我们将 UI 划分为独立的、可重用的部分,并且可以对每个部分进行单独的思考。
在实际应用中,组件常常被组织成层层嵌套的树状结构:
组件定义:
定义一个单组件文件.vue:
<script>
import {ref} from 'vue'
//计数器
const count = ref{0}
</script>
<template>
<button @click="count++">num of click times:{{count}}</button>
</template>
组件使用:
在其他文件中通过import导入,导入后可多次引用:
<script>
//导入单组件文件
import base_5 from './components/base_5.vue'
</script>
<template>
<h1>Here is a basic module!</h1>
<base_5/>
<base_5/>
</template>
传递props
为了在相同视觉下不同内容的情况,通过注册props,自定义attribute传递不同的内容。
子组合文件声明props并引用:
<script setup>
import { defineProps } from 'vue'
defineProps(['title'])
</script>
<template>
<h4> {{title}} </h4>
<button @click="$emit('enlarge-text')">Enlarge text</button>
</template>
父文件可以通过数组传递title内容,使用v-for渲染:
<script setup>
//导入单组件文件
import base_5 from './components/base_5.vue'
import {ref} from 'vue'
const posts = ref([
{ id: 1, title: 'Props——title1' },
{ id: 2, title: 'Props——title2' },
{ id: 3, title: 'Props——title3' }
])
</script>
<template>
<div>
<h1>Here is a basic module!</h1>
<base_4_module v-for="post in posts" :key="post.id" :title="post.title"/>
</div>
</template>
监听
父组件通过v-on 或@自定义attribute监听,监听到即触发公式:
<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>