vue 使用 element-ui 表单常见问题

194 阅读1分钟

一、表单 input 和 select 宽度不一致(不美观):

解决方法:

1、input 加 suffix-icon="xxx"

2、select加:style="100%"

二、表单 resetFields 重置清空无效:

1、el-form 中使用注意事项:

(1)  model 中的字段要和 ref中 的字段对应上,model 中的字段也就是 v-model 中监听的对象的字段。

(2) prop 中的字段要和 v-model 中的字段对应上,这个四个字段都是为了做验证或重置使用

2、resetFields() 使用注意事项:

(1) resetFields()只是重置,重置为初始值。

() 这个初始值是在form表单created时确定的,如果在created的时候赋值了,

那么在以后的重置的时候都不会重置为空字符串。

(3) 在进行编辑的时候需要在打开form表单的时候对输入框赋值,那么赋值动作就

是在created的时候进行的, 那么在以后重置的时候都不会重置为空字符串了。

解决方法:

方法1: 利用this.$nextTick()将赋值操作放到dom渲染结束之后

方法2:在 mounted 中再给表单对象赋值,而不是在 created 中

三、input[type = "number"] 鼠标滚动时值跟着改变:

需求:改成 鼠标滚动,input 值不变,只滚动页面

实现步骤:

1. 监听mousewheel事件

2. 获取input输入框元素

3. 当监听到鼠标滚动事件时,设置input元素失去光标

解决方法:

1、注册全局 mousewheel 自定义指令

import type {Directive} from 'vue';
const stopMousewheel:Directive = {    
    updated:function (el:HTMLElement) {        
        el.addEventListener('mousewheel',() => {            
        const elem:any = el.tagName === 'INPUT' ? el : el.querySelector('input'); 
        elem.blur();        
    })    
}};
export default stopMousewheel;

2、在 DOM el-input 中加入 v-stopMousewheel 即可

四、input[type = "number"] 输入中文时焦点上移:

解决方法:
<style scoped>
::v-deep .el-input__inner {
    line-height: 1px !important;
}
</style>

五、单独清除/校验 表单某个字段:

1、校验某个字段:this.$refs['formData'].validateField('name');
2、清除某个字段校验:this.$refs['formData'].clearValidate(['name']);