vue3 setup 语法糖 的 props、emit 练习

本文探讨了在Vue 3的setup语法糖中如何实现父子组件间的通信,通过定义props和emits,以及使用`@carried`进行事件触发。展示了如何在子组件中定义props并触发父组件的自定义事件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

父组件App.vue

<script setup>
import HelloWorld from './components/HelloWorld.vue'

function carried(value) {
  alert(`牛呀,都实现了!!!${value}`)
}
</script>

<template>
  <p>❀❀❀❀❀❀❀❀❀❀❀❀---app--vue---❀❀❀❀❀❀❀❀❀❀❀</p>

  <HelloWorld msg="Vite + Vue" wish="不掉发" wishes="变瘦" @carried="carried">
    <h3>实现插槽1</h3>

    <template v-slot:dome>
      <h4>实现插槽2</h4>
    </template>
  </HelloWorld>

  <p>❀❀❀❀❀❀❀❀❀❀❀❀---app--vue---❀❀❀❀❀❀❀❀❀❀❀</p>
</template>

<style scoped>
* {
  color: red;
}
</style>

子组件 

在setup 语法糖中,setup可以接收两个参数,第一个参数是 props,也就是组件传值;第二个参数是context,上下文对象,context里面还有三个很重要的东西attrsslotsemit

它们分别通过defineProps、defineEmits、defineExpose 获取,无需引入

<script setup>
import { ref } from 'vue'
defineProps({
  msg: String,
  wish: String,
  wishes: String
})
const emit = defineEmits(['carried'])

function dream() {
  emit('carried', 666)
}
</script>

<template>
  <p>=================helloworld================</p>
  <h1>{{ msg }}</h1>
  <button @click="dream">点击实现</button>
  <slot></slot>
  <slot name="dome"></slot>
  <p>=================helloworld================</p>
</template>

<style scoped>
* {
  color: aqua;
}
button {
  background-color: aqua;
  color: white;
}
</style>

预览

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

记忆怪 bug

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值