vue3.2中的defineProps、defineEmits、defineExpose

前言

大家都听说了v3.2中的 script setup 语法糖,当开发中用到组件传值,事件传递的时候突然发现不知所措,不必恐慌,或查官网或记住以下3个api,大部分问题又迎刃而解了。

defineProps

获取组件传值

<template>
  <h1>{{ msg }}</h1>
  <div @click="clickThis">1111</div>
</template>

<script setup lang="ts">
  defineProps<{ // 采用ts专有声明,无默认值
    msg: string,
    num?: number
  }>()
     // 采用ts专有声明,有默认值
    interface Props {
        msg?: string
        labels?: string[]
    }
    const props = withDefaults(defineProps<Props>(), {
        msg: 'hello',
        labels: () => ['one', 'two']
    })
    
  defineProps({ // 非ts专有声明
    msg: String,
    num: {
      type:Number,
      default: ''
    }
  })
</script>

<style scoped lang="less">
</style>

defineEmits

子组件向父组件事件传递

<template>
  <div @click="clickThis">点我</div>
</template>

<script setup lang="ts">
    /*ts专有*/
  const emit= defineEmits<{
    (e: 'click', num: number): void
  }>()
    /*非ts专有*/
  const emit= defineEmits(['click'])
  
  const clickThis = () => {
    emit('click',2)
  }
</script>

<style scoped lang="less">
</style>

defineExpose

子组件暴露自己的属性

<template>
  <div>子组件helloword.vue</div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
const count = ref(123456)
defineExpose({
  count
})
</script>

<style scoped lang="less">
</style>

父组件获取属性

<template>
  <div @click="helloClick">父组件</div>
  <helloword ref="hello"></helloword>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import helloword from './components/HelloWorld.vue'
const hello = ref(null)
const helloClick = () => {
  console.log(hello.value.count) // 123456
}
</script>


<style lang="less" scoped>
</style>

点赞加关注,永远不迷路

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 前言 您将在本文当中了解到,往网页中添加数据,从传统的dom操作过渡到数据层操作,实现同一个目标,两种不同的方式....
    itclanCoder阅读 25,905评论 1 12
  • 1. 前言 vue也是组件化开发框架,对于这种组件化开发来说,组件之间的通信方式通常都是非常重要的所以单独开一个篇...
    云高风轻阅读 1,983评论 0 13
  • 一:什么是闭包?闭包的用处? (1)闭包就是能够读取其他函数内部变量的函数。在本质上,闭包就 是将函数内部和函数外...
    xuguibin阅读 9,737评论 1 52
  • 目录 1.vue-router是怎么传递参数的 2.v-if和v-for一起使用的弊端以及解决办法 3.befor...
    裁尘的人儿阅读 1,070评论 1 5
  • 一:什么是闭包?闭包的用处? (1)闭包就是能够读取其他函数内部变量的函数。在本质上,闭包就 是将函数内部和函数外...
    彩云_789d阅读 999评论 0 1