互联网技术 · 2024年2月20日

使用render函数在Vue中为子组件设置ref操作

这篇文章主要介绍了在vue中通过render函数给子组件设置ref操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

正常我们的写法是,这样ref不会生效,h是作用在渲染的时候的,而ref是渲染之后才创建的,因此在h函数中使用ref是无效的。

render: (h, params) => {
      
 return h(expandRow, {
   ref:child,
   props: {
     row: params.row
   } 
 }) 
}

我们常见h函数的用法是:

render: (h) => {
  return h(ele)
}

=> 是es6的用法,相当于 (h) => {} 相当于 function(){},上面的代码可解析为:

render: function(createElement) {
  return createElement(ele);
}

Vue在创建Vue实例时,通过render作为函数来渲染Dom树,而在render方法中,又调用createElement函数来渲染子组件或元素。

因此此时元素或子组件处于渲染过程。

ref是用来给元素或子组件注册引用信息的,引用信息将会注册在父组件的$refs对象上。

因为 ref 本身是作为渲染结果被创建的,在初始渲染的时候你不能访问它们 – 它们还不存在!

解决办法

把h改为创建 this.$createElement

render: (h, params) => {
      
 return this.$createElement(expandRow, {
   ref:child,
   props: {
     row: params.row
   }
 
 }) 
}

补充知识: Vue 里怎样在 Render 中使用 $refs

背景:

使用 element-ui 组件,发现el-popover组件有一个方法: doClose();调用方法为:this.refs[name].doClose();经过测试正常使用是没问题的。现在想要在组件内的render函数中调用,一直获取不到this.refs[name].doClose();经过测试正常使用是没问题的。

现在想要在组件内的render函数中调用,一直获取不到this.refs[name].doClose();经过测试正常使用是没问题的。现在想要在组件内的render函数中调用,一直获取不到this.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);
         }
    &nbsp

OpenMagic API

Need more than content? Move into the product flow.

If you are here for model access, pricing, developer docs, or the future API console, the dedicated product path now lives on api.openmagic.ai.

登录免费注册