Vue解決父組件清空子組件的表單驗證


1.頁面上就一個簡單的按鈕 

 

 

 

2..當點擊“顯示子組件”按鈕時,顯示出被隱藏的表單

3.當用戶直接點擊”登錄”按鈕時,顯示校驗的錯誤信息

 

4.用戶直接點擊“隱藏”按鈕時,表單被隱藏。但存在一個bug,當再次點擊“顯示子組件”的時候,表單上的錯誤信息仍然存在。因此需要清空掉子組件的表單錯誤信息

 

代碼如下:

父組件:
<template>
    <div>
      <div>
        <el-button @click="showForm" type="primary" size="">清空子組件里面的form表單的驗證</el-button>
      </div>
      <NewForm ref="newForm" v-show="isShow" @hidden="hidden"></NewForm>
    </div>
</template>

<script>
import NewForm from '@/components/NewForm'
export default {
  name: 'HelloTest',
  components: {
    NewForm
  },
  // eslint-disable-next-line space-before-function-paren
  data() {
    return {
      isShow: false
    }
  },
  methods: {
    showForm () {
      this.isShow = true
      this.$refs.newForm.$refs.refForm.clearValidate()
    },
    hidden () {
      this.isShow = false
    }
  }
}
</script>

<style scoped>

</style>

 

子組件:

<template>
  <div style="margin-top: 10px">
    <div style="min-width: 500px;max-width:800px;border: solid 1px #000;margin-left:auto;margin-right: auto">
      <el-form :model="form" :rules="rules" ref="refForm" label-width="80px" style="margin-top: 20px;margin-right: 20px;">
        <el-form-item label="用戶名" prop="username">
          <el-input v-model="form.username"></el-input>
        </el-form-item>

        <el-form-item label="密碼" prop="password">
          <el-input v-model="form.password" type="password"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button @click="hidden">隱藏</el-button>
          <el-button @click="doLogin" type="primary">登錄</el-button>
        </el-form-item>

      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  name: 'NewForm',
  data () {
    return {
      // 表單的基本屬性
      form: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '請輸入用戶名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '請輸入密碼', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    doLogin () {
      this.$refs.refForm.validate((valid) => {
        if (valid) {
          this.$message({message: '登錄成功', type: 'success'})
        } else {
          this.$message({message: '登錄失敗', type: 'error'})
        }
      })
    },
    hidden () {
      this.$emit('hidden')
    }
  }
}
</script>

<style scoped>

</style>

 

1.在子組件上添加ref的屬性,然后通過 this.$refs.屬性名,獲取子組件的DOM的所有元素 以上代碼的寫法為 this.$refs.newForm

2.獲取子組件DOM的節點后,然后在通過$refs獲取子組件里面的表單ref屬性的DOM節點   最后 代碼的寫法為 this.$refs.newForm.$refs.refForm。

這樣就獲取了子組件里面表單的DOM節點,便可以對子組件表單進行操作。如清空表單驗證的操作等

 

注:clearValidate()的方法必須在element-ui 2.0以上


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM