# Cascader
# 级联选择使用演示
# 以省市区为例
# 预览:
# 代码:
<template>
<div>
<g-cascader :source.sync="source"
popover-height="200px"
:selected.sync="selected"
:load-data="loadData">
</g-cascader>
</div>
</template>
<script>
import GCascader from 'cascader'
import db from 'db'
function ajax(parentId = 0) {
return new Promise((resolve, reject) => {
let result = db.filter((item) => item.parentId == parentId)
result.forEach(item => {
if (db.filter(node => node.parentId === item.id).length > 0) {
item.isLeaf = false
} else {
item.isLeaf = true
}
})
resolve(result)
})
}
export default {
components: {GCascader},
data() {
return {
selected: [],
source: []
}
},
created() {
ajax(0).then((result) => {
this.source = result
})
},
methods: {
loadData({id}, updateSource) {
ajax(id).then((result) => {
setTimeout(() => {
updateSource(result)
}, 1000)
})
}
}
}
</script>
# 说明
- 上例模拟创建一个db库,通过创建的ajax API来请求获取相应数据;
- 数据结构:
[{
id: 1,
name: "四川",
parentId: 0,
isLeaf: false
},{
id: 2,
name: "成都",
parentId: 1,
isLeaf: false
},{
id: 3,
name: "锦江区",
parentId: 2,
isLeaf: true
},{
id: 4,
name: "青羊区",
parentId: 2,
isLeaf: true
}]
- 动态获取子元素:loadData(selectedItem, callbackFn)
loadData({id}, updateSource){
ajax(id).then((result) => {
setTimeout(() => {
updateSource(result)
}, 1000)
})
}
通过selectedItem.id作为parentId为依据,去获取到selectedItem的children,再利用回调执行callbackFn(children)。
# API
# Cascader
参数 | 说明 | 类型 | 默认值 |
---|---|---|---|
source | 级联展开的最外面一层数据,通常parentId为0 | Array | 无 |
popoverHeight | 级联弹框高度需要给定 | String | 100px |
selected | 监听当前所选中的内容 | Array | 无 |
loadData | 动态获取子元素,并执行回调,loadData(selectedItem, callbackFn) | Function | 无 |