props 父传子
- js - defineComponent
import { defineComponent } from 'vue'
export default defineComponent({
props: {
foo: String,
bar: {
type: Number,
default: () => 1
}
}
})
- ts - defineComponent
import { defineComponent } from 'vue'
export default defineComponent({
props: {
foo: String,
bar: {
type: String,
required: true
},
}
})
// 复杂类型
import { defineComponent } from 'vue'
import type { PropType } from 'vue'
interface Foo{
name: string,
age: number
}
export default defineComponent({
props: {
foo: {
type: Object as PropType<Foo>,
default: () => {}
},
callback: Function as PropType<(id: string) => void>
}
})
- js - <script setup></script>
<script setup>
const props = defineProps({
foo: String,
bar: {
type: Number,
default: () => 1
}
})
</script>
- ts - <script setup lang='ts'></script>
<script setup lang='ts'>
interface Props {
foo: string,
bar?: number
}
const props = defineProps<Props>()
</script>
// 解构默认值
<script setup lang='ts'>
interface Props {
foo: string,
bar?: number
}
const props = withDefaults(defineProps<Props>(), {
foo: 'abc',
bar: 12
})
</script>
emit 子传父
- js - defineComponent
export default defineComponent ({
emits: ['change']
setup(props, { emit }){
emit('change')
}
})
- js - <script setup></script>
<script setup>
const emit = defineEmits(['change'])
emit('change)
</script>
- ts - <script setup lang='ts'></script>
const emit = defineEmits<
change: [id: number]
>()
// 或者
const emit = defineEmits<{
(e: 'change', id: number): void
}>()
</script>
ref 父组件获取子组件数据
- 子组件向外暴露
const a = 2
const b = () => {}
defineExpose({
a,
b
})
- 父组件通过 ref 获取
<template>
<child ref="childRef"></child>
</template>
<script setup>
import { ref } from 'vue'
const childRef = ref()
childRef.value.a // 获取
</script>
网友评论