vue组件之间的传值
父传子
父组件
<child :list='list'></child>
<script>
let list:number[] = [1,2,3]
</script>
子组件 接参方式有两种
1,直接在defineProps函数内定义
defineProps({
list:number[]
})
2,对象字面量的形式
type Props = {
list:number[] // 定义一个类型 用于defineProps接参对象的类型
}
defineProps<Props>()
完毕后直接在子组件页面使用即可 如果要设置接参的默认值,可以用withDefaults
withDefautls(defineProps<Props>{},{
// 此处指定参数的默认值
lsit=()=>[1,1,1,1,1] //引用数据类型用 箭头函数return出来
})
子传父
子组件
<templete>
<button @click='send'>子组件向父组件派发事件</button>
</templete>
<script>
let str:string='我是子组件参数'
const emit = defineEmits(['fatherFun'])
const send = ()=>{
emit('fatherFun',str) // 第一个参数是子组件派发的函数名(子传父是通过函数事件派发)
}
</script>
父组件
<child @fatherFun='getChildData' ></child> // 子组件
<script>
const getChildData = (val)=>{ // val 子 组件传递的参数
console.log(val)
}
</script>
子传子
兄弟组件传值可以有两种方式实现
兄弟A传值到共同父组件,然后父组件传值到兄弟B组件
使用$Bus时间总线
type BusClass<T> = {
emit: (name: T) => void
on: (name: T, callback: Function) => void
}
type BusParams = string | number | symbol
type List = {
[key: BusParams]: Array<Function>
}
class Bus<T extends BusParams> implements BusClass<T> {
list: List
constructor() {
this.list = {}
}
emit(name: T, ...args: Array<any>) {
let eventName: Array<Function> = this.list[name]
eventName.forEach(ev => {
ev.apply(this, args)
})
}
on(name: T, callback: Function) {
let fn: Array<Function> = this.list[name] || [];
fn.push(callback)
this.list[name] = fn
}
}
export default new Bus<number>()
本作品采用《CC 协议》,转载必须注明作者和本文链接
关于 LearnKu
推荐文章: