vue + ant 级联选择器动态加载 组件方式

vue组件代码 CategoryCascader.vue

<template>
  <div>
    <a-form-model-item label="产品分类" prop="categoryId">
      <a-cascader :style="'width:'+width+'px'" @blur="blur()" 
      @click="handleClick()" :popupVisible="popupVisible" 
      allowClear :options="options" 
      :load-data="loadData" placeholder="请选择" change-on-select @change="onChangeCascader" 
      :fieldNames="{ label: 'categoryNameCn', value: 'id', children: 'children' }" />
    </a-form-model-item>
  </div>
</template>
<script>
import { selectCategoryGoods, selectCategoryGoodsByFatherId} from '../../api/product/getProductList'   // 接口 查询
export default {
  props: {
    width: Number
  },
  name: 'index',
  data () {
    return {
      selectCascader: [],
      popupVisible: null,
      stopUpload: false,
      options: [],
      categoryId: ''
    }
  },
  methods: {
  //失去焦点 关闭popup
    blur () {
      this.popupVisible = false
    },
    //点击级联打开popup并加载父级分类
    handleClick () {
      this.popupVisible = true
      this.getCategory()
    },
    
    /* 获取父级分类 */
    getCategory () {
      selectCategoryGoods().then(res => {
        this.options = res.data.map(item => {
          item.isLeaf = false
          return item
        })
        this.options = res.data
      })
    },

    /* 分类级联选择器 */
    onChangeCascader (value) {
      this.selectCascader = value //存储所选数组id
      this.categoryId = value[value.length - 1]  //取最后一位给后台查询
      // console.log('选中的id', this.categoryId);
      this.$emit('onChangeCascader', this.categoryId)
    },

    /* 动态加载 */
    async loadData (e) {
      const targetOption = e[e.length - 1]
      targetOption.loading = true
      let data = await selectCategoryGoodsByFatherId({ fatherId: targetOption.id }) 
      //接口调用
      console.log('data', data);
      targetOption.loading = false
      if (data.data.length == undefined) {
        this.popupVisible = false
        targetOption.loading = false
        return
      }

      data.data.forEach(item => {
        item.isLeaf = false
        targetOption.loading = false
      })
      targetOption.children = [...data.data]
      this.options = [...this.options]
    },
  },
}
</script>
<style  scoped>
</style>

2.组件调用

<template>
	<div>
	<a-form-model>
		<CategoryCascader @onChangeCascader="onChangeCascader" />
	</a-form-model>
	</div>
</template>
<script>
import CategoryCascader from './CategoryCascader.vue'
export default {
	name: 'index',
   components: { CategoryCascader },
   methods:{
   	  onChangeCascader (categoryId) {
      consol.log(categoryId) //拿到的三级id
    },
   }
}
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一头小绵羊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值