老师们好,我用el-form封装了一个组件, 父组件想调用这个组件的的this.$refs['formRef'].resetFields() 方法, 测试了一些方法都不好用想请老师们给一个思路,谢谢啦。这个环境是用vue2.
下面是封装子组件的代码:
<template>
<el-form :model="formModel" ref="formRef" :rules="formRules" :label-width="formData.labelWidth">
<el-form-item :label="item.label" :prop="item.prop" v-for="(item, k) in formData.items" :key="k">
<!-- 输入框 或文本域-->
<el-input
v-if="item.type === 'input'"
v-model="formModel[item.prop]"
:type="item.inputType"
:maxlength="item.maxlength"
:minlength="item.minlength"
:placeholder="item.placeholder"
:clearable="item.clearable"
:size="item.size"
:showWordLimit="item.showWordLimit"
:disabled="item.disabled"
:style="{ width: item.width }"
:rows="item.rows"
>
</el-input>
<!-- 下拉选择 -->
<el-select v-model="formModel[item.prop]" :placeholder="item.placeholder" v-if="item.type === 'select'">
<el-option :label="o.label" :value="o.value" v-for="(o, k) in item.options" :key="k" :disabled="item.disabled"></el-option>
</el-select>
<!-- 开关 -->
<el-switch v-model="formModel[item.prop]" :disabled="item.disabled" v-if="item.type === 'switch'"></el-switch>
<!-- 单选框 -->
<el-radio-group v-model="formModel[item.prop]" v-if="item.type === 'radio'">
<el-radio :label="o.value" v-for="(o, k) in item.options" :key="k">{{ o.label }}</el-radio>
</el-radio-group>
<!-- 多选框 -->
<el-checkbox-group v-model="formModel[item.prop]" v-if="item.type === 'checkbox'">
<el-checkbox :label="o.value" v-for="(o, k) in item.options" :key="k">{{ o.label }}</el-checkbox>
</el-checkbox-group>
</el-form-item>
</el-form>
</template>
<script>
export default {
name: 'EForm',
// components: { EInput },
props: {
formData: {
type: Object,
required: true,
default: () => {}
},
formModel: {
type: Object,
required: true,
default: () => {}
},
formRules: {
type: Object,
required: false,
default: () => {}
}
},
data() {
return {}
},
mounted() {
// console.log('this.ref: ', this.$refs)
// const entries = Object.entries(this.$refs['formRef'])
// for (const [key, value] of entries) {
// this[key] = value
// }
},
methods: {
childMethod() {
// this.$refs
this.$refs['formRef'].resetFields()
},
validateFormItem() {
this.$refs['formRef'].validate(valid => {
this.$emit('validateForm', valid, this._props.formModel)
})
}
}
}
</script>
<style lang="sass" scoped></style>
你需要在 methods 里面定义一个 resetFields 啊。
不然的话,就是
this.$refs['formRef'].$refs['formRef'].resetFields
这种形式。你可以 console 一下看看或者用 vue 的浏览器插件看就懂了