美文网首页
iview踩坑

iview踩坑

作者: Clover园 | 来源:发表于2019-04-02 17:44 被阅读0次

1、iview三级联动,删除效果实现

需求:省市区的三级联动,并且有删除效果,执行删除时,后面的一项也需要删除;当改变省份的时候,市和区都要改变,当改变市的时候,县/区也要改变。用到的就是iview下拉框的属性:删除clearable和clearSingleSelect()

<template>
  <div id="app">
    <Form  v-model="formItem">
      <Row>
        <Col span="5">
          <FormItem label="省">
            <Select v-model="formItem.province" style="width:200px" @on-change="changeProvince" clearable filterable>
              <Option v-for="item in dataArea" :value="item.value" :key="item.value">{{ item.label }}</Option>
            </Select>
          </FormItem>
        </Col>
        <Col span="5">
          <FormItem label="市">
            <Select v-model="formItem.city" style="width:200px"  @on-change="changeCity" clearable filterable ref='selectEl'>
              <Option v-for="item in cityList" :value="item.value" :key="item.value">{{ item.label }}</Option>
            </Select>
          </FormItem>
        </Col>
        <Col span="5">
          <FormItem label="区/县">
            <Select v-model="formItem.county" style="width:200px" clearable filterable ref='selectcounty'>
              <Option v-for="item in districtList" :value="item.value" :key="item.value">{{ item.label }}</Option>
            </Select>
          </FormItem>
        </Col>
      </Row>
    </Form>
  </div>
</template>

js

<script>
  import axios from 'axios';
export default {
  name: 'App',
  components: {
 
  },
  data(){
    return{
      dataArea:[],
 
      formItem:{
        province:'',
        city:'',
        county:'',
      },
      cityList:[],
      districtList:[]
    }
  },
  created(){
    this.iniDate()
  },
  methods:{
    //省市区初始化
    iniDate() {
      axios.get('../static/region.json').then(res => {
        this.dataArea = res.data;
      })
    },
    changeProvince: function (value) {
      this.cityList=[];
      this.districtList=[];
      this.$refs.selectEl.clearSingleSelect();
      this.$refs.selectcounty.clearSingleSelect();
      let length = this.dataArea.length;
      if (value) {
        for (let i = 0; i < length; i++) {
          if (value == this.dataArea[i].value) {
            this.cityList = this.dataArea[i].children;
          }
        }
      }
    },
    changeCity: function (value) {
      this.districtList=[];
      this.$refs.selectcounty.clearSingleSelect();
      let length = this.cityList.length;
      if (value) {
        for (let i = 0; i < length; i++) {
          if (value == this.cityList[i].value) {
            this.districtList = this.cityList[i].children;
          }
        }
      }
    },
  }
}
</script>
image.png
使用起来也比较简单,就是在需要删除的那段代码上加上标识:ref,然后在执行事件时,使用下段代码即可:
 this.$refs.selectcounty.clearSingleSelect();

2、iview使用第三方自定义的iconfont图标

iview是支持引入第三方iconfont图标的,具体如何使用?

(1)将字体图表文件和css文件放入static文件夹下。(有时候需要在css里改一下font字体文件的路径)

(2)在需要引入的页面引入css文件。(比如:import '../static/style.css')

(3)在需要使用字体图标的地方引入icon的class名即可。比如:(<Icon custom="icon-10" size="24" />)

3、iview的表单校验问题

iview的表单校验步骤:

(1)给 外层的Form 设置属性 :model='formValidate';属性 :rules :'ruleValidate'; 属性ref='formValidate'

<Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80">
(2)在需要校验的 FormItem 设置属性 prop 指向对应字段即可 prop=“”。需要注意的是:formItem的prop属性值必须和下面的v-model字段对应。

<FormItem label="Name" prop="name">
    <Input v-model="formValidate.name" placeholder="Enter your name"></Input>
</FormItem>

(3)在data里添加校验规则

ruleValidate: {
     name: [
           { required: true, message: 'The name cannot be empty', trigger: 'blur' }
          ],
}

(4)事件中校验

handleSubmit (name) {
      this.$refs[name].validate((valid) => {
         if (valid) {
             this.$Message.success('Success!');
         } else {
              this.$Message.error('Fail!');
         }
        })
},
handleReset (name) {
      his.$refs[name].resetFields();
}

注意:(1)如果v-model并不是像上面那样,只是单字段的,是两层对象的,类似这样:

v-model="formItem.plantVo.cropsTypeId"

那么formItem的prop属性也要写成:prop='plantVo.cropsTypeId',并且在data校验时,加引号,否则校验不通过

'plantVo.cropsTypeId': [
     { required: true, message: "请填写作物种类", trigger: "change",type:'number' }
],

(2)在校验过程中,要时刻注意trigger的类型,是click事件还是change事件,需要注意type的数据类型,是字符串还是数字类型。

自定义校验

自定义校验的规则和一般校验类似,不过也有区别,我们来验证一个input框的年龄问题

<template>
  <Form ref="formCustom" :model="formCustom" :rules="ruleCustom" :label-width="80">
    <FormItem label="年龄" prop="age">
      <Input type="text" v-model="formCustom.age" number></Input>
    </FormItem>
    <FormItem>
      <Button type="primary" @click="handleSubmit('formCustom')">提交</Button>
    </FormItem>
  </Form>
</template>
<script>
export default {
  data() {
    const validateAge = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("年龄不能为空"));
      } else if (!Number.isInteger(value)) {
        callback(new Error("请填写数字"));
      } else if (value < 18) {
        callback(new Error("年龄必须大于18"));
      } else {
        callback();//必须加上。否则填写成功后会一直转圈,点击不成功
      }
    };
    return {
      formCustom: {
        age: ""
      },
      ruleCustom: {
        age: [{ validator: validateAge, trigger: "blur" }]
      }
    };
  },
  methods: {
    handleSubmit(name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          this.$Message.success("提交成功!");
        } else {
          this.$Message.error("提交失败!");
        }
      });
    }
  }
};
</script>

写法并不复杂。value表示填写的值,callback()表示填写之后的回调返回值,rule表示这个对象。但我们在校验的时候,如果成功,必须加上callback().也就是这一块


image.png

否则,填写完成之后,会一直转圈,并不能校验成功。


image.png

4、modal关闭问题

需求:modal框需要做校验处理,如果校验成功则向后台提交并关闭modal;校验不成功则弹出提示,不关闭modal。

问题:使用modal的v-model来处理并不能达到预期效果,校验不成功依然会关闭modal

解决:1、使用slot自定义的按钮实现;2、给modal添加一个loading状态,通过这个状态来控制显示隐藏,不过这个状态也有一定的规范。

<template>
  <div id="app">
    <Button type="primary" @click="btn">确定</Button>
    <Modal 
    v-model="modal1" 
    title="填写信息" 
    @on-ok="ok('form')" 
    @on-cancel="cancel"
    :loading='loading'
    >
      <Form :model="form" ref="form" :rules="rule">
        <FormItem label="年龄" :label-width="80" prop="formInput">
          <Input v-model="form.formInput"/>
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>
<script>
export default {
  data() {
    return {
      modal1: false,
      loading:true,//初始化时必须设置为true,否则第一次还是会关闭
      form: {
        formInput: ""
      },
      rule: {
        formInput: [{ required: true, message: "不能为空", trigger: "blur" }]
      }
    };
  },
  methods: {
    btn() {
      this.modal1 = true;
    },
    ok(name) {
      this.$refs[name].validate(valid => {
        if (valid) {
           this.loading = false;
           this.modal1 = false;
        } else {
           this.loading = false;
           this.$nextTick(() => {
            this.loading = true;
          });
        }
      });
    },
    cancel() {}
  }
};
</script>

在验证失败的时候,也就是else里加上:

this.loading = false;
           this.$nextTick(() => {
            this.loading = true;
          });

给model加上loading状态,初始化的时候,一定要设置loading为true,否则第一次还是会关闭。可参考:https://github.com/iview/iview/issues/597

5、row-class-name的使用

iview的表格提供了row-class-name属性,可以改变表格行的样式问题。用法如下:

<Table :row-class-name="rowClassName" :columns="columns1" :data="data1"></Table>

 methods: {
            rowClassName (row, index) {
                if (index === 1) {
                    return 'demo-table-info-row';
                } else if (index === 3) {
                    return 'demo-table-error-row';
                }
                return '';
            }
        }

这是最简单的使用。如果将表格封装成组件形式,然后改变多个行的样式。使用方法就不一样了。
1、首先在表格组件中,在组件的props中定义,type=Funtion

 <Table stripe :columns="columns" :data="listData" :row-class-name="mydefineRow" ></Table>

export default {
        name: '',
        props: {
            listData: {
                default: []
            },
            columns: {
                default: []
            },
            rowClassName:{
                type:Function,
                default(){
                    return ''
      }
   }
},

2、在引入组件的页面,使用本地缓存获取点击的表格行的id

removeSessionStore('selectId');
setSessionStore('selectId', params.row.id)

3、在表格组件的初始化时,获取这个id

if(getSessionStore('selectId')){
    let selectId = getSessionStore('selectId');
    if(selectId){
         this.selectId=selectId;
    }
}

4、在表格组件中,写入相应的事件

mydefineRow(row,index){
 
    if(row.id==this.selectId){
      return 'demo-table-info-row'
    }else if (row.farmerIdentityId==this.selectId){
      return 'demo-table-info-row'
    }
     return ''
},

注意:使用row.id来进行比较,不能使用index索引。上面只改变一个。如果想改变多个,思路也是一样的。将点击的id放入到数组ids中,然后在mydefineRow方法中,循环这个ids数组,然后判断

mydefineRow(row,index){
                
for(let i = 0;i<this.selectIds.length;i++){
 if(row.id===this.selectIds[i]){
      return 'demo-table-info-row'
 }
}
  return ''
},

上面不管是改变一行,还是改变多行,搞定。
6、iview动态生成的menu导航,opennames不能自动展开的问题
最近有个需求就是要做管理后台的自动登录功能。当用户在登录网站时,勾选了自动登录按钮,当浏览一段时间后,关闭网页,下次再通过链接进入时,自动展开打开的左侧导航。open-names和active-name都已经获取到。但依然不行,解决:

获取到两个值后,在menu上加上ref='side_menu',在mounted()里还需要手动更新。

this.$nextTick(() => {
    this.$refs.side_menu.updateOpened();
    this.$refs.side_menu.updateActiveName();
});

特别需要注意的是:open-names的值是数组类型,active-name的值是字符串或数字类型。但是,open-names数组里面的元素的数据类型必须和active-name的数据类型一致。否则能获得焦点,但是父级菜单并不会自动展开。

出处https://blog.csdn.net/weixin_38384967/article/details/83109703

2019/10/23
在tab页里面嵌入select下拉框,切换select总是没消失,查了好久才发现问题,改个下面样式transition: all 0s ease-in-out就行了

.ivu-tabs{
      height:calc(100% - 42px);
      .ivu-select-selection,.ivu-select-arrow,.ivu-checkbox-inner,.ivu-checkbox-checked .ivu-checkbox-inner:after,.ivu-input-search{
        transition: all 0s ease-in-out
      }
    }

2020/4/14
提示message消息总是被遮罩层弹窗遮盖问题
iview的弹窗层级是共享的,所以一直有这个问题,添加一个customClass:zZindex

 if(this.formItem.featureType===""){
        this.$message({message: this.$t('models.params.tip.selectEigenvalues'),type: 'warning',customClass: 'zZindex'});
        return;
      }

//zZindex写在全局样式里面
.zZindex{
  z-index:9999999999!important;
}

相关文章

网友评论

      本文标题:iview踩坑

      本文链接:https://www.haomeiwen.com/subject/pxtnbqtx.html