Vue3中ref的使用

2021-06-29  本文已影响0人  小俊的世界

引言

使用ElForm进行表单的验证时,之前在vue2中,则是采用的是this.$refs['form'].validate,但是在vue3 的setup中是没有办法直接使用this,如何进行解决?

使用ref变量

 <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-position="center"
        size="small"
        label-width="100px"
      >
     ...
</el-form>

setup(){
   const formRef = ref(null);
   const save = () => {
        (formRef.value as any)?.validate((valid) => {
          if (valid) {
             console.log('验证通过')
          }
        });
      };
  return {
     formRef,
     save
  }
}

需要注意的是,ref前面是没有:,而ref是一个变量的,这个是有些反直觉的。

使用 getCurrentInstance

  import {  getCurrentInstance } from 'vue';
  setup(){
     const instance = getCurrentInstance()
     const save = () => {
        (instance?.refs['formRef'] as any)?.validate((valid) => {
          if (valid) {
             console.log('验证通过')
          }
        });
     }
  }

需要注意的是 getCurrentInstance是有使用的限制的,如果是直接在方法中书写是直接拿不到值的,比如下面这种写法,直接放在了save方法中,是不行的

 import {  getCurrentInstance } from 'vue';
  setup(){
     
     const save = () => {
        const instance = getCurrentInstance() // 获取不到当前上下文 
        (instance?.refs['formRef'] as any)?.validate((valid) => {
          if (valid) {
             console.log('验证通过')
          }
        });
     }
  }

总结

在vue3的setup中可以使用ref变量的方式或者getCurrentInstance两种方式来使用Ref,从使用方便的程度上来看,更加推荐使用ref变量的方式。

上一篇下一篇

猜你喜欢

热点阅读