需求:此级联选择器一共有两层数据,父节点的数据和子节点的数据分别从不同接口获取。
效果:
template中:
<el-form-item label="分支">
<el-cascader ref="casader" v-model="params.projectVersionId" :props="childrenProps" :options="projectList"
:show-all-levels="false" key="casader" v-loadCascader="loadMore" clearable filterable
:before-filter="beforeFilter" @input.native="inputEnter" placeholder="请选择分支" @change="projctChangeFn">
</el-cascader>
</el-form-item>
script中:
export default {
data() {
return {
params: {
projectVersionId: ''
},
// 父节点-筛选
projectList: [],
maxPage: '', // 接口返回最大有几页(每页10条数据)
projectParams: {
pageNo: 1,
limit: 10,
projectName: '',
resourceCode: 1
},
// 子节点-筛选
childrenProps: {
lazy: true,
leaf: 'leaf',
lazyLoad: (node, resolve) => {
if (!node.value) {
return
}
const data = {
isStrategy: false
}
this.$api.taskApi
.taskVersion(node.value,data)
.then((res) => {
if (res.data) {
const nodes = res.data.map(item => ({ label: item.versionName, value: item.id, leaf: 1 }))
resolve(nodes);
}
})
.catch((res) => {
this.$message({
message: res.msg,
type: 'error'
})
resolve([]);
})
}
}
}
},
mounted() {
this.init()
},
methods: {
init() {
this.getProjectListFn();
},
// 获取父级节点列表
getProjectListFn() {
this.$api
.projectList(this.projectParams)
.then((res) => {
if (res.data && res.data.list) {
this.maxPage = Math.ceil(res.data.total / 10)
let newData = this.handleProjectData(res.data.list)
this.projectList.push.apply(this.projectList, newData)
}
})
.catch(() => {
this.projectList = []
})
},
handleProjectData(data) {
return data.map(item => {
return { label: item.name, value: item.id, children: [] }
})
},
// 下滑加载更多
loadMore() {
if (this.projectParams.pageNo < this.maxPage) {
this.projectParams.pageNo++
this.getProjectListFn()
}
},
beforeFilter() {
return false;
},
//模糊搜索
inputEnter() {
let ref = this.$refs["casader"];
setTimeout(() => {
this.projectList = []
this.projectParams.pageNo = 1
this.projectParams.projectName = ref.inputValue
this.getProjectListFn()
});
},
projctChangeFn(val) {
this.params.projectVersionId = val.length == 2 ? val[1] : ''
this.$refs.table.loadData({ ...this.params })
},
}
}
main.js中新增一个el-cascader的下滑触底事件
// el-cascader 滚动加载更多
Vue.directive("loadCascader", {
bind(el, binding) {
const cascaderDom = el.querySelector(
".el-cascader__dropdown .el-cascader-menu__wrap"// 滚动条所在元素
);
if (cascaderDom) {
cascaderDom.addEventListener("scroll", function () {
const condition =
this.scrollHeight - this.scrollTop <= this.clientHeight;
if (condition) {
let temp = this.scrollTop;
binding.value();
setTimeout(() => {
this.scrollTop = temp + 100;// 滚动加载更多时,显示的数据在上次位置基础上往上滑动100
}, 0)
}
})
}
}
})
补充:
在el-cascader中使用lazyLoad,使用箭头函数的形式,里面的this指向就不会有问题。