1. 父传子 - defineProps
1.1 js 中的写法
// App.vue
<template>
<Child :title="title"></Child>
</template>
<script setup>
import { ref } from "vue"
import { Child } from "..."
let title = ref<string>("标题")
</script>
// Child.vue
<template>
<div>{{ title }}</div>
</template>
<script setup>
const props = defineProps({
title: {
type: String,
default: "默认值"
}
})
console.log(props.title)
</script>
1.2 ts 中的写法
<template>
<Child :title="title" :arr="[1,2,3]"></Child>
</template>
<script setup lang="ts">
import { ref } from "vue"
import Child from "..."
let title = ref<string>("标题")
</script>
// Child.vue
<template>
{{ title }}
{{ arr }}
</template>
<script setup lang="ts">
const props = withDefaults(defineProps<{
title: String,
arr: number[]
}>(), {
title: () => "默认值",
arr: () => [4,5,6]
})
console.log(props.title, props.arr)
</script>
2. 子传父 - defineEmits
2.1 js 中的写法
<template>
<Child @on-click="receive"></Child>
</template>
<script setup>
import Child from "..."
const receive = (...args) => {
console.log("我是父组件,收到了")
console.log(...args)
}
</script>
<template>
<button @click="send"></button>
</template>
<script setup>
const emit = defineEmits(['on-click'])
const send = () => {
emit("on-click", "value1", "value2")
}
</script>
2.2 ts 中的写法
<template>
<Child @on-click="receive"></Child>
</template>
<script setup lang="ts">
import Child from './components/Child.vue'
function receive(){
console.log("我是父组件,收到了")
console.log(...arguments)
}
</script>
<template>
<button @click="send">给父组件传值</button>
</template>
<script setup lang="ts">
const emit = defineEmits<{
(e:"on-click", param1: string, param2: string):void
}>()
const send = () => {
let param1 = "value1"
let param2 = "value2"
emit("on-click", param1, param2)
}
</script>
3. 子组件给父组件暴露属性和方法 - defineExpose
// App.vue
<template>
<Child ref="childRef"></Child>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import Child from './components/Child.vue'
const childRef = ref<InstanceType<typeof Child>>()
onMounted(() => {
console.log(childRef.value?.name, childRef.value?.open)
})
</script>
// Child.vue
<script setup lang="ts">
defineExpose({
name: 'lzy',
open: () => console.log(111)
})
</script>