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>