vue3中defineExpose的使用方法

文章介绍了在Vue移动端项目中,如何通过父组件调用子组件PopAddress.vue的弹出框功能,以及使用TS编写的组件通信和数据处理示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

之前写人力资源的移动端用到了这个,其实很多地方都用到了,这个比较难就是。

(代码有带你找不到了,随便找一个实例吧!)

比如这个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。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值