使用的是Vue3+Ts
1. 父 ---- 传 ---- 子
父组件
<child :list='list'></child>
<script>
let list:number[] = [1,2,3]
</script>
子组件
子组件接参 使用 defineProps()
接参方式有两种
接参方式有两种
- 直接在defineProps函数内定义
defineProps({
list:number[]
})
- 对象字面量的形式
type Props = {
name?:string // 非必传
list:number[] // 定义一个类型 用于defineProps接参对象的类型
}
defineProps<Props>()
完毕后直接在子组件页面使用即可
如果要设置接参的默认值,可以用withDefaults
withDefautls(defineProps<Props>{},{
// 此处指定参数的默认值
name:"",
list = ()=>[1,1,1,1,1] //引用数据类型用 箭头函数return出来
})
2. 子 ---- 传 ----父
子组件
<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>
3. 兄弟 ---- 传 ----兄弟
兄弟组件传值可以有两种方式实现
- 兄弟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>()
然后挂载到Vue config 全局就可以使用啦
详情参考 [小满zs] 博客
https://xiaoman.blog.csdn.net/article/details/123158620