vue3基础_$event、ref、fragment和teleport

文章介绍了Vue3中的双向绑定语法糖,$event在父子组件通信中的作用,如何通过ref获取DOM元素,父传子的ref使用,组件间通信的defineExpose,无根标签的Fragment片段,以及Teleport功能,用于解决HTML结构嵌套问题并实现跨组件交互。

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

1. 双向绑定语法糖
在这里插入图片描述
2. $event 永远表示子组件进行$emit 的时候的第二个参数

// App.vue
<script setup>
import { ref } from 'vue'
import Child from './Child.vue'

const count = ref(1)
// 需求:希望 count 传递给子组件,子组件也要修改这个count

</script>
<template>
  <div>
  // 这儿的 $event 永远表示子组件进行 $emit 的时候的第二个参数
     <Child :count="count" @changeCount="count = $event">
  </div>
</template>
// Child.vue
<script setup>
  defineProps(['count'])
</script>
<template>
  <div> 
     count:{{ count }}
     <button @click="$emit('changeCount',8)">改为8
  </div>
</template>

3.如何获取DOM
ref获取Dom

import { onMounted, ref } from 'vue'
// 1.建立一个 ref 引用
co**加粗样式**nst oDiv = ref(null)

onMounted(()=>{
 // 3.oDiv.value就是divDom
  oDiv.value.style.backgroundColor = 'deeppink'
})

<template>
// 2.用 oDiv 和 div 的ref属性进行绑定
  <div ref="oDiv">Hello</div>
</template>

4.ref进行父传子

在这里插入图片描述
5.使用defineExpose进行导出

在这里插入图片描述
6.fragment片段
vue3组件可以没有根标签,其内部会将多个标签包含在一个 fragment 虚拟元素中
减少内存占用以及不必要的层级嵌套

7.teleport
传送,能将特定的 html 结构(一般是嵌套很深的)移动到指定的位置,解决 html 结构嵌套过深照成的样式影响或不好控制的问题
传送到body里面:

// Dialog.vue
<template>
  <teleport to = "body">
     <div>Dialog</div>
  </teleport>
</template>
<template>
  <div class="child">
    <Dialog v-if="bBar" />
    <button @click="handleDialog">显示弹框</button>
  </div>
</template>

<script>
import { ref } from 'vue'
import Dialog from './Dialog.vue'
export default{
  name:'Child',
  components:{
    Dialog
  },
  setup(){
   const bBar = ref(false)
   const handleDialog = () =>{
     bBar.value = !bBar.value
    }
    return {
      bBar,
      handleDialog
    }
  }
}
</script>

7.在App.vue 的 parent上面加点击事件,相当于直接在parent.vue 的根组件加点击事件

<template>
  <div>
     <Parent @click="handleClick" />
  </div>
</template>

<script setup>
import Parent from './Parent.vue'
const handleClick = () => {
   console.log(1)
}
</script>
<template>
  <div>
  // 点击p就会触发handleClick事件
     <p>1</p>
     <p>2</p>
  </div>
</template>

<script>
export default{
// 明确告诉它是自定义的,那handleClick的点击就不会生效
 // emits['click']
}
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值