1.父组件给子组件传值
官方文档
const props = defineProps<{
menuList: number[]
menuAllList: menuType[]
}>()
const props = defineProps({
menuList: {
type: Array,
required: true,
},
menuAllList: {
type: Array,
default(){
return []
},
},
})
<template>
<!-- parent.vue -->
<child :menuList="menuList" :menuAllList="menuAllList"></child>
</template>
2.子组件给父组件传值
const emit = defineEmits(['closeTree'])
function closeTree() {
const obj = {
val: '需要传给父组件的值',
}
emit('closeTree', obj)
}
function closeTree(val) {
console.log('子组件传递过来的值', val)
}
```vue
<template>
<child @closeTree="closeTree"></child>
</template>
3.使用依赖注入方式进行传值
import { ref, provide } from 'vue'
provide('test', '123456')
const count = ref(100)
provide('count', count)
provide('speak', () => {
console.log('函数')
})
import { inject } from 'vue'
const test = inject('test')
const count = inject('count')
4.在ts中使用依赖注入方式进行传值
import { InjectionKey } from 'vue'
interface person {
name: string;
age: number;
}
export const personKey: InjectionKey<person> = Symbol('person')
import { provide } from 'vue'
import { personKey } from '@/utils/symbols'
provide(personKey, {
name: '张三',
age: 18,
})
import { inject } from 'vue'
import { personKey } from '@/utils/symbols'
const person = inject(personKey)
console.log(person.name)