語法糖內的defineProps及defineEmits、defineExpose

defineProps

獲取組件傳值

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

<script setup lang="ts">
  defineProps<{ // 采用ts專有聲明,無默認值
    msg: string,
    num?: number
  }>()

defineProps<{ title?: string, hello?: (string | 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(['clickThis'])
  
  const clickThis = () => {
    emit('clickThis',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>
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容