(uniapp)基于vue3父子组件间传递参数与方法
基于vue3父子组件间通信(uniapp)
一、父传子
父组件
在父组件中使用子组件,并将父组件中的变量progressNow
传递到子组件progress
的prop上
import Progress from '@/components/Progress.vue'
<Progress :progress="progressNow"></Progress>
子组件
子组件prop接收progress
并在html中使用
const props = defineProps({progress:Number
})
<view class="progress-bar-content" :style="{width:progress*10+'%'}"></view>
二、子传父
子组件
在子组件中声明变量和方法,并将变量和方法暴露出去
const activeIndex = ref(0)
const handleSelect = ()=>{...方法逻辑
}
defineExpose({activeIndex,handleBack
})
父组件
- 首先在父组件中声明组件实例
- 其次将组件实例与组件绑定
- 最后通过组件实例在父组件中使用在子组件中声明的变量和方法
// 声明组件实例
const subjectRef = ref(null)
// 绑定
<subject ref="subjectRef"></subject>
// 使用子组件中的变量和方法
subjectRef.value.activeIndex
subjectRef.value.handleBack()
三、子组件的变量与父组件的变量动态建立联系
子组件的变量与父组件的变量动态建立联系(即子组件变量变化父组件变量随之变化)
使用computed方法
const progressNow = computed(()=>{// 确保组件实例已挂载if(subjectRef.value && subjectRef.value.activeIndex){return subjectRef.value.activeIndex}// 当组件还未挂载时直接返回0else{return 0}
})
如果不对组件实例是否挂载进行判断是会报错的
当组件实例没有挂载,activeIndex这个在子组件中声明的变量还是undefined,将undefined赋给父组件变量就会报错