vue3 中的defineProps、defineEmits、defineExpose

defineProps

获取组件传值

复制代码
 1 <template>
 2   <h1>{{ msg }}</h1>
 3   <div @click="clickThis">1111</div>
 4 </template>
 5 
 6 <script setup lang="ts">
 7   defineProps<{ // 采用ts专有声明,无默认值
 8     msg: string,
 9     num?: number
10   }>()
11      // 采用ts专有声明,有默认值
12     interface Props {
13         msg?: string
14         labels?: string[]
15     }
16     const props = withDefaults(defineProps<Props>(), {
17         msg: 'hello',
18         labels: () => ['one', 'two']
19     })
20     
21   defineProps({ // 非ts专有声明
22     msg: String,
23     num: {
24       type:Number,
25       default: ''
26     }
27   })
28 </script>
29 
30 <style scoped lang="less">
31 </style>
复制代码

defineEmits

子组件向父组件事件传递

复制代码
 1 <template>
 2   <div @click="clickThis">点我</div>
 3 </template>
 4 
 5 <script setup lang="ts">
 6     /*ts专有*/
 7   const emit= defineEmits<{
 8     (e: 'click', num: number): void
 9   }>()
10     /*非ts专有*/
11   const emit= defineEmits(['click'])
12   
13   const clickThis = () => {
14     emit('click',2)
15   }
16 </script>
17 
18 <style scoped lang="less">
19 </style>
复制代码

defineExpose

子组件暴露自己的属性

复制代码
 1 <template>
 2   <div>子组件helloword.vue</div>
 3 </template>
 4 
 5 <script setup lang="ts">
 6 import { ref } from 'vue'
 7 const count = ref(123456)
 8 defineExpose({
 9   count
10 })
11 </script>
12 
13 <style scoped lang="less">
14 </style>
复制代码

父组件获取属性

复制代码
 1 <template>
 2   <div @click="helloClick">父组件</div>
 3   <helloword ref="hello"></helloword>
 4 </template>
 5 
 6 <script setup lang="ts">
 7 import { ref } from 'vue'
 8 import helloword from './components/HelloWorld.vue'
 9 const hello = ref(null)
10 const helloClick = () => {
11   console.log(hello.value.count) // 123456
12 }
13 </script>
14 
15 
16 <style lang="less" scoped>
17 </style>
复制代码

转自:https://www.jianshu.com/p/04ce44cc7ed8

posted @   虚无——缥缈  阅读(329)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
点击右上角即可分享
微信分享提示