[{"createTime":1735734952000,"id":1,"img":"hwy_ms_500_252.jpeg","link":"https://activity.huaweicloud.com/cps.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905","name":"华为云秒杀","status":9,"txt":"华为云38元秒杀","type":1,"updateTime":1735747411000,"userId":3},{"createTime":1736173885000,"id":2,"img":"txy_480_300.png","link":"https://cloud.tencent.com/act/cps/redirect?redirect=1077&cps_key=edb15096bfff75effaaa8c8bb66138bd&from=console","name":"腾讯云秒杀","status":9,"txt":"腾讯云限量秒杀","type":1,"updateTime":1736173885000,"userId":3},{"createTime":1736177492000,"id":3,"img":"aly_251_140.png","link":"https://www.aliyun.com/minisite/goods?userCode=pwp8kmv3","memo":"","name":"阿里云","status":9,"txt":"阿里云2折起","type":1,"updateTime":1736177492000,"userId":3},{"createTime":1735660800000,"id":4,"img":"vultr_560_300.png","link":"https://www.vultr.com/?ref=9603742-8H","name":"Vultr","status":9,"txt":"Vultr送$100","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":5,"img":"jdy_663_320.jpg","link":"https://3.cn/2ay1-e5t","name":"京东云","status":9,"txt":"京东云特惠专区","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":6,"img":"new_ads.png","link":"https://www.iodraw.com/ads","name":"发布广告","status":9,"txt":"发布广告","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":7,"img":"yun_910_50.png","link":"https://activity.huaweicloud.com/discount_area_v5/index.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=aXhpYW95YW5nOA===&utm_medium=cps&utm_campaign=201905","name":"底部","status":9,"txt":"高性能云服务器2折起","type":2,"updateTime":1735660800000,"userId":3}]
最近几个月都在用TS开发各种项目,框架有涉及到Vue3,React18等;
记录一下Vue/React组件暴露出变量/函数的方法的写法;
Vue2
回顾一下Vue2 组件暴露出去方法,它并没有约束,写在methods里的方法都能被调用,data里的变量也能被接收;
现拉一个vue 2.6.10的模板下来
子组件的数据
父组件获取子组件实例,调用子组件方法等;
控制台输出:
这个输出的子组件实例里包含所有的变量和方法;
Vue3
组件通过vue3提供的defineExpose方法,把需要暴露出去的函数/变量放入到该方法里;
<script setup lang="ts"> import { defineExpose, ref } from 'vue'; ... // 举个例子
const name = ref('ikun'); function setName(name: string) { name.value = name; }
defineExpose({ name, setName }) </script>
父组件
同样在子组件上声明一个ref对象接收这个子组件实例;为了能自动识别出暴露的方法,需要指定这个ref对象的类型;
此时可以在任意方法里访问这个子组件暴露出来的数据
<script setup lang="ts"> import { ref } from 'vue'; interface ChildInstance {
name: string setName: (name: string) => void } const child = ref<ChildInstance >
(); // 调用此方法即可改变子组件里的数据 function test() { child.value?.setName('xxx') console.
log(child.value?.name) } </script> <template> ... <Child ref="child" /> </
template>
React
react函数式组件已经跟vue3差不多了,只不过是名字不一样而已;
在react中,通过useImperativeHandle这个hook+高阶组件formRef来暴露出组件的方法;
贴一下某个业务代码片段
子组件暴露出去的方法
这其中BasicImpHandle 就是暴露的方法类型接口;
父组件
render
Vue3和React获取的子组件实例不会像Vue2那样暴露全部的方法和数据了,只会暴露定义好的数据出来,感觉更安全吧;
就酱.