el-cascader 使用笔记-5.使用实例(封装组件)

(1)组件 components下创建目录DivisionCascader,DivisionCascader下创建index.vue,代码如下

参考:https://blog.****.net/Binglianxiaojiao/article/details/143017798

<template>
  <el-cascader :value="value" :props="props"  @change="handleChange" style="width: 100%;" clearable filterable placeholder="请选择行政区划"/>
</template>

<script>
import {findAll} from "@/api/expertveteran/division";

export default {
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    value: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      props: {
        lazy: true,
        lazyLoad (node, resolve) {
          let value=node.value==undefined?"":node.value;
          findAll(value).then(res=>{
            const nodes=res.data;
            // 通过调用resolve将子节点数据返回,通知组件数据加载完成
            resolve(nodes);
          })
        }
      },
    }
  },
  methods: {
    handleChange(val) {
      this.$emit('change', val);
    }
  }
}
</script>

(2)main.js

import DivisionCascader from "@/components/DivisionCascader"

// 全局组件挂载
Vue.component('DivisionCascader', DivisionCascader)

(3)使用

<el-form-item label="行政区划" prop="divisionCode">
  <division-cascader v-model="form.divisionCode"/>
</el-form-item>

(4)其他相关

division.js

import request from '@/utils/request'

// 查询行政区划列表
export function findAll(code) {
    return request({
        url: '/expertveteran/division/findAll?code='+code,
        method: 'get',
    })
}


// 编码处理
export function handleCode(code) {
    if (Array.isArray(code)){
      return code[code.length-1]
    }
    if (code.length==6){
      return [code.substr(0,2),code.substr(0,4),code.substr(0,6)]
    }
    if (code.length==9){
      return [code.substr(0,2),code.substr(0,4),code.substr(0,6),code.substr(0,9)]
    }
}

编码处理

import {handleCode} from "@/api/expertveteran/division";
/** 修改按钮操作 */
handleUpdate(row) {
  this.reset();
  const id = row.id || this.ids
  getExpertInfo(id).then(response => {
    this.form = response.data;
    this.form.divisionCode=handleCode(this.form.divisionCode);
    this.open = true;
    this.title = "修改专家信息";
  });
},
/** 提交按钮 */
submitForm() {
  this.$refs["form"].validate(valid => {
    if (valid) {
      this.form.divisionCode=handleCode(this.form.divisionCode)
      if (this.form.id != null) {
        updateExpertInfo(this.form).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.open = false;
          this.getList();
        });
      } else {
        addExpertInfo(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      }
    }
  });
},
上一篇:axios vue.js


下一篇:【AI编程实战】安装Cursor并3分钟实现Chrome插件(保姆级)