vue3父子组件传值

117 阅读1分钟

1.父组件给子组件传值

官方文档

// child.vue 接收父组件参数
// ts中需要声明类型
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.子组件给父组件传值

// child.vue
// 需要将事件名注册
const emit = defineEmits(['closeTree'])
function closeTree() {
  const obj = {
    val: '需要传给父组件的值',
  }
  emit('closeTree', obj)
}
// parent.vue
function closeTree(val) {
  console.log('子组件传递过来的值', val)
}
```vue
<template>
  <child @closeTree="closeTree"></child>
</template>

3.使用依赖注入方式进行传值

// parent.vue
import { ref, provide } from 'vue'
// provide() 接受两个参数:第一个参数是要注入的 key,可以是一个字符串或者一个 symbol,第二个参数是要注入的值。注入的值可以是对象,函数等
// 提供静态值
provide('test', '123456')
// 提供响应式的值 provide('count', count.value)的方式不保持响应式
const count = ref(100)
provide('count', count)
provide('speak', () => {
  console.log('函数')
})
// child.vue
import { inject } from 'vue'
// parent.vue 注入的值
const test = inject('test') // 123456
const count = inject('count') // ref对象

4.在ts中使用依赖注入方式进行传值

// ts中使用provide,inject
// symbols.ts 文件
import { InjectionKey } from 'vue'
interface person {
  name: string;
  age: number;
}
export const personKey: InjectionKey<person> = Symbol('person')
// parent.vue
import { provide } from 'vue'
import { personKey } from '@/utils/symbols'
provide(personKey, {
  name: '张三',
  age: 18,
})
// child.vue
import { inject } from 'vue'
import { personKey } from '@/utils/symbols'
const person = inject(personKey)
console.log(person.name)