Vue3笔记:基础组件

组件概述

组件允许我们将 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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值