Vue 里怎样在 Render 中使用 $refs

tech2025-08-05  11

背景:

使用 element-ui 组件,发现el-popover组件有一个方法: doClose();调用方法为:this. r e f s [ n a m e ] . d o C l o s e ( ) ; 经 过 测 试 正 常 使 用 是 没 问 题 的 。 现 在 想 要 在 组 件 内 的 r e n d e r 函 数 中 调 用 , 一 直 获 取 不 到 t h i s . refs[name].doClose();经过测试正常使用是没问题的。 现在想要在组件内的render函数中调用,一直获取不到this. refs[name].doClose()使renderthis.refs[name],报undefined

解决思路:
添加vue-DevTools工具,查看$refs属性下是否存在该元素,分析Dom元素存在的位置,进行逐层分解打印当前render下的this,发现并没有当前元素的相关属性,so: this指向没有问题,但并非是我们的Dom元素理解Vue.component和render所创建的组件的关系和指向问题,render相当于是在当前的父组件内创建了子组件解决方式:this.$refs[父组件ref名].refs[子组件ref名]+方法属性
代码结构:
// 父组件TableList内的属性 <template> <el-card class="auto-schedu-class"> <TableList border ref="TableList" :columns="columns(this)" /> </el-card> </template> <script> const columns = that => [ { render: (h, parmas) => { return h( "el-popover", { ref: "popover", props: { placement: "top", width: "160" } }, [ h("p", "当前规则生效中,是否确认删除?"), [ h( "el-button", { props: { type: "text", size: "mini" }, on: { click: row => { console.log(this, "-------------"); that.handleDeleteRow(row); } } }, "取消" ), h( "el-button", { props: { type: "text", size: "mini" } }, "确定" ) ], h( "el-button", { props: { type: "text", size: "mini" }, slot: "reference" }, "删除" ) ] ); } } ]; export default { data() { return { columns }; }, methods: { handleDeleteRow(row) { console.log(this, "======="); this.$refs.TableList.$refs.popover.doClose(); // 获取到子组件内的属性方法 } } }; </script>
vue-DevTools元素层级分析总结:

作者也看了好多类似的文章,并没有找到一个合理的解决方式和解析文章通过我们的vue工具,逐层进行元素的拆解,证明我们的refs元素是存在的,so:Dom的一种解析加载方式和层级关系就是我们的一个思路点,很多文章归结在this的指向上面,而render的创建和vue.component的关系才是我们的突破点
最新回复(0)