之前写人力资源的移动端用到了这个,其实很多地方都用到了,这个比较难就是。
(代码有带你找不到了,随便找一个实例吧!)
比如这个pop的弹出框
这是父组件
<templete>
<div class="sf-right" @click="popOpen">选择地址</div>
<pop-address ref="addressPop" :createOrder="openPop" />
</templete>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import PopAddress from '@/components/pop/PopAddress.vue'
const childeRef = ref()
onMonted(() => {
childeRef.value.dataList([{id:1,name:'hello'}])//调用子组件函数
})
const openPop = () => {
if (point.value >= total.value) {
pointPop.value.open()
} else {
payPop.value.open()
}
}
const popOpen = async () => {
const arr = shopCart.value.filter((x: { is_real: number }) => x.is_real)
if (arr.length > 0) {
// 选择收货地址
return addressPop.value.open()
}
openPop()
}
</script>
这是子组件
<template>
<uni-popup ref="pop" background-color="#fff" type="center">
<div class="cars-page">
<div class="car-info">选择地址</div>
<div class="ci-active" v-for="(item, index) in dataList" :key="index" @click="handle(item, index)"
:class="{ active: activeIndex == index }">
<address-card :value="item" v-model:id="id" />
</div>
<div class="save-btn" @click="confirm">确定</div>
</div>
</uni-popup>
</template>
<script lang="ts" setup>
import { ref } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import AddressCard from '@/components/card/AddressCard.vue'
import { addressSelect, addressDel } from '@/api/address'
const props = defineProps({
addressId: {
type: Number,
default: 0
},
createOrder: {
type: Function
}
})
const dataList = ref<any>([])
const pop = ref()
// 选中id
const id = ref()
const emit = defineEmits(['update:addressId'])
defineExpose({
close: () => {
pop.value.close()
},
open: () => {
pop.value.open()
}
})
const activeIndex = <any>ref(0)
const property = <any>ref('')
const titleindex = ref(0)
const handle = (item: any, index: any) => {
activeIndex.value = index
property.value = item
titleindex.value = index
}
const confirm = () => {
const address = dataList.value[activeIndex.value].id
emit('update:addressId', address)
pop.value.close()
props.createOrder && props.createOrder()
}
const getCarsList = async () => {
const result = await addressSelect()
if (result.code == 1) {
dataList.value = result.data
}
}
onMounted(() => {
getCarsList()
})
</script>
子组件defineExpose暴露响应式数据a和方法loadList,父组件ref获取子组件实例可以调用当前子组件暴露出来的数据a和方法dataList。