前言
大家都聽說了v3.2中的
script setup
語法糖幌墓,當(dāng)開發(fā)中用到組件傳值,事件傳遞的時候突然發(fā)現(xiàn)不知所措冀泻,不必恐慌常侣,或查官網(wǎng)或記住以下3個api,大部分問題又迎刃而解了弹渔。
defineProps
獲取組件傳值
<template>
<h1>{{ msg }}</h1>
<div @click="clickThis">1111</div>
</template>
<script setup lang="ts">
defineProps<{ // 采用ts專有聲明胳施,無默認(rèn)值
msg: string,
num?: number
}>()
// 采用ts專有聲明,有默認(rèn)值
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">點(diǎn)我</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>
點(diǎn)贊加關(guān)注肢专,永遠(yuǎn)不迷路