vue3 向外暴露子组件方法和变量

第一步:在子组件中暴露

方法一

<script setup lang="ts">
const name ="abc";
const getData= () => {}
defineExpose({
  getData,
  name
})
</script>

方法二

defineComponent({
 	setup(props, ctx) {
		const name ="abc";
	 	const getData= () => {}
	  	ctx.expose({getData,name})
 	}
})

第二步:在父组件中使用

<template>
<image-preview ref="imgRef" />
</template>
<script setup lang="ts">
import { ref } from 'vue'
const imgRef = ref(null);
const preview=()=>{
  console.log(imgRef.value.name)
  console.log(imgRef.value.getData())
}
Vue3 中,子组件想要将其定义的方法暴露给父组件以便在父组件中调用,可以通过以下几种方式: 1. **props**(属性)传递:虽然不是直接暴露方法,但子组件可以通过 `methods` 对象中的方法作为 props 传递给父组件。父组件可以在接收到这些 prop 后,创建一个事件监听器来调用子组件方法。 ```javascript // 子组件 <template> <button @click="handleClick">点击我</button> </template> <script setup> import { ref } from &#39;vue&#39;; export default { methods: { handleClick() { // ... } }, props: { callMe: { type: Function, required: true, } } }; </script> // 父组件 <template> <ChildComponent :callMe="handleClickFromParent" /> </template> <script> function ParentComponent() { const handleClickFromParent = () => { console.log(&#39;从父组件调用了子组件方法&#39;); }; return { components: { ChildComponent }, methods: { handleClickFromParent } }; } </script> ``` 2. **自定义事件**($emit):子组件可以定义一个或多个自定义事件,当方法被触发时,通过 `$emit` 发送到父组件。父组件可以监听这些事件并执行相应操作。 ```javascript // 子组件 <template> <button @click="$emit(&#39;custom-event&#39;, &#39;method-called&#39;)">点击我</button> </template> <script> export default { emits: [&#39;custom-event&#39;] }; </script> // 父组件 <template> <ChildComponent @custom-event="handleCustomEvent" /> </template> <script> const ParentComponent = { methods: { handleCustomEvent(event, method) { console.log(`从子组件 ${method} 被调用了`); } } }; </script> ``` 3. **ref on**(仅适用于 composition API):如果子组件是函数式组件,可以使用 `on` 方法 `ref` 来暴露方法,这种方式更接近于React的生命周期管理。 ```javascript // 子组件 (composition API) <script setup> import { onMounted } from &#39;vue&#39;; import { ref } from &#39;vue&#39;; const handleClick = () => { // ... }; onMounted(() => { window.handleClick = handleClick; }); </script> <!-- 父组件 --> <template> <ChildComponent /> </template> <script> const ChildComponent = { name: &#39;ChildComponent&#39;, }; </script> ``` 然后在父组件中,你可以通过全局变量 `window.handleClick` 来调用子组件方法
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值