### 子组件中应该保证将方法通过defineExpose传递
特点:可以直接在父组件中使用子组件的方法和变量,如下例,在调用了两个方法后,会自动调用子组件中的 isLegal 方法 ,并不需要将isLegal() 暴露出去,也就是说,相当于父组件调用暴露方法时,是通过子组件的代码进行的
const handletouchstart = (e) => {
startX = e.changedTouches[0].pageX
startY = e.changedTouches[0].pageY
console.log("start======>",e.changedTouches[0].pageX , e.changedTouches[0].pageY)
starttime = Date.now()
}
const handletouchend = (e) => {
endtime = Date.now()
endX = e.changedTouches[0].pageX
endY = e.changedTouches[0].pageY
// console.log("end======>",e.changedTouches[0].pageX , e.changedTouches[0].pageY)
if(isLegal() === 'right'){
console.log("right")
}else if(isLegal() === 'left'){
console.log("left")
}else{
console.log("no")
}
}
const isLegal = () =>{
if(endtime - starttime > 5000){
return false;
}
if(Math.abs(endX - startX)>50){
let dir = endX - startX > 0 ? 'right' : 'left';
return dir;
}else{
return false;
}
}
// 使用expose直接暴露函数,但是只能通过ref绑定dom元素去使用
defineExpose({
handletouchend,
handletouchstart,
})·
### 父组件中只能通过ref绑定子组件标签,获取其中方法(使用方式,通过定义新的方法名,调用子组件dom元素中携带的方法)
// 注意:dom元素的绑定是在onMounted 周期后的
onMounted(()=>{
console.log(swiperaction.value)
// const handletouchstarts = swiperaction.value.handletouchstart()
})
// 使用expose暴露的方法
// const handletouchstarts = (e) =>{
// swiperaction.value.handletouchstart(e)
// console.log(22)
// }
·
###### 间接使用(通过子组件返回状态来控制父标签中的行为)
实现方式:slot插槽
原理:通过slot插槽将父组件内的页面元素放入子组件中,进而保证子组件可以通过在slot标签外嵌套view标签,直接使用在子组件中定义的方法,再通过defineEmits,将处理结果返回父组件,父组件通过接受该状态判断如何进行下一步渲染.(类似于,消息发布行为)
该方式的优点为,避免直接暴露方法带来的不安全,并且简化了上述步骤,减少了耦合代码