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 @ 2023-05-10 14:25  虚无——缥缈  阅读(323)  评论(0编辑  收藏  举报