父组件向子组件传值
1.简单的props方式
//fater.vue
<div class="father">
<children :carr="arr" />
</div>
<script setup lang="ts">
import children from './children.vue'
const arr = [1, 3, 5]
//children.vue
<div class="children">
<div>carr:{{ carr }}</div>
</div>
<script setup lang="ts">
defineProps({
carr: {
type: Array,
required: true
}
})
子组件向父组件传值
1.函数方式
//fater.vue
<div class="father">
<children :carr="fatherFun" />
</div>
<script setup lang="ts">
import children from './children.vue'
const fatherFun = (n: number) => {
console.log('父组件函数,接收到子组件的值为:', n)
}
//children.vue
<div class="children">
<div @click="onUp(3)">carr:</div>
</div>
<script setup lang="ts">
const props = defineProps({
carr: {
type: Function,
required: true
}
})
function onUp(n: number) {
console.log('子组件函数')
props.carr(n)
}
/*
结果为:
子组件函数
父组件函数,接收到子组件的值为: 3
*/
2.emit方式
//father.vue
<div class="father">
<children :carr="arr" @getChildren="oncFun" />
</div>
<script setup lang="ts">
import children from './children.vue'
const arr = [1, 3, 5]
function oncFun(x: number) {
console.log('父组件函数,接收到子组件的值为:', x)
}
//children.vue
<div class="children">
<div @click="onUp(3)">carr:</div>
</div>
<script setup lang="ts">
const props = defineProps({
carr: {
type: Array,
required: true
}
})
//setup中使用emits,需要先声明,定义属性数量
const emits = defineEmits(['getChildren'])
function onUp(n: number) {
console.log('子组件函数')
emits('getChildren', n)
}
3.provide和inject
适用于层级比较多,如爷孙组件传值。结合传函数的方式,可以让爷孙组件相互传值
父组件
provide('stateFun', (x) => {
console.log('x',x)
})
孙组件
Function代表注入的是函数,true代表有传入参数
const stateFun = inject('stateFun', Function, false)
stateFun('abc')
用provide和inject 会遇上类型问题,子组件接收到的是unknown类型
所以用 InjectionKey 类型声明来定义值(做名称)
**新建一个type.ts**
import { InjectionKey, Ref } from 'vue'
export interface User {
name: string
age: number
}
// 对象的InjectionKey
export const userKey: InjectionKey<Ref<User>> = Symbol('')
**父组件中**
const user = ref({ name: 'tom', age: 20 })
provide('user', user) //普通的传值
provide(userKey, user) //类型声明的传值
**子组件中**
import { userKey } from './type'
const user: any = inject('user') //user: unknown 无法点操作,所以声明为any
console.log('inject:', user.value.name) //tom
const user2 = inject(userKey) //user2: Ref<User> | undefined
console.log('injectKey:', user2) // RefImpl {...}
vuex或pinia方式