モバイル版の人材管理システム開発でこの機能を使用したことがあるが、実際にはさまざまな場面で利用されている。この概念は少し理解しにくい部分がある。
(コードは見つからなかったので、例として以下のようなものを使う)
例えばこのポップアップダイアログの場合
親コンポーネントのコード
<template>
<div class="sf-right" @click="popOpen">住所を選択</div>
<pop-address ref="addressPop" :createOrder="openPop" />
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import PopAddress from '@/components/pop/PopAddress.vue'
const childRef = ref()
onMounted(() => {
childRef.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="popup" 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 popup = ref()
// 選択されたID
const id = ref()
const emit = defineEmits(['update:addressId'])
defineExpose({
close: () => {
popup.value.close()
},
open: () => {
popup.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)
popup.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とメソッドloadListを呼び出すことができる。