Vue3.x+Element-Plus通过render函数创建表单ref的问题?

作者站长头像
站长
· 阅读数 12

代码:

<script>
import { defineComponent, ref, reactive, h, onMounted, nextTick } from 'vue'
import { ElForm } from 'element-plus'

export default defineComponent({
  components: {
    ElForm
  },
  setup () {
    const ruleFormRef = ref(null)
    const ruleForm = reactive({
    })

    const rules = reactive({
    })
    const handleClick = () => {
      // 表单校验
      console.log('ruleFormRef.value111:', ruleFormRef.value) //值为null
    }
    return {
      ruleFormRef,
      ruleForm,
      rules,
      handleClick
    }
  },
  render () {
    const btnChildren = <el-button onClick={this.handleClick}>提交</el-button>
    return h(ElForm, {
      ref: this.ruleFormRef,
      model: this.ruleForm,
      rules: this.rules,
      labelWidth: '120px',
      class: 'demo-ruleForm'
    }, [btnChildren])
  }
})
</script>

进行表单提交校验,打印出来的ruleFormRef.value的值为null。该怎么处理?

回复
1个回答
avatar
test
2024-07-05

将代码改成这样就可以了


return h(ElForm, {
      ref: (el) => this.ruleFormRef = el,
      model: this.ruleForm,
      rules: this.rules,
      labelWidth: '120px',
      class: 'demo-ruleForm'
    }, [btnChildren])
回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容