element el-cascader 動態加載次級選項,防止重復加載,異步請求三級數據
本篇文章解決的問題:
1,綁定事件@active-item-change點擊后無反應
2,需要動態加載到第三級,官網例子只給了第二級,比如(省、市、區)(頂級分類、二級分類、三級分類)
3,已經加載過的數據防止重復加載
下面是代碼
<template> <el-cascader :options="platOptions" @active-item-change="handleItemChange" :props="props"></el-cascader> </template> <script> export default { data () { return { platOptions: [], props: { label: 'name', value: 'id', children: 'child' } } }, methods: { getPlatCategory () { // 請求頂級分類 this.$axios.get('/api/getCategory') .then(res => { if (res.status === 200) { this.platOptions = res.data.data this.platOptions.map((item, index, array) => { // 因為數組和對象更新后不會更新視圖,這里必須用$set方法 this.$set(array[index], 'child', []) }) } }).catch(error => { let langmsg = this.$i18n.locale === 'zh' ? error.data.zhmsg : error.data.enmsg this.$message.error(langmsg) }) }, handleItemChange (value) { // 動態/異步加載分類數據 let parentId if (value.length === 1) { // 如果點擊的是一級分類 parentId = value[0] this.platOptions.map((item, index) => { if (item.id === parentId && item.child.length === 0) { // 當頂級分類的的child為空時才請求數據 this.$axios.get('/api/getCategorySon', { params: { parent_id: parentId } }).then(res => { if (res.status === 200) { this.$set(this.platOptions[index], 'child', res.data.data) item.child.map((innerItem, innerIndex) => { // 二級分類下必須要設置一個空的child數組,不然點擊@active-item-change沒反應 this.$set(item.child[innerIndex], 'child', []) }) } }) } }) } else { // 如果點擊的是二級分類,則直接將三級分類綁定到platOptions parentId = value[1] this.platOptions.map((item, index) => { item.child.map((innerItem, innerIndex) => { if (innerItem.id === parentId && innerItem.child.length === 0) { // 當二級分類的的child為空時才請求一次數據 this.$axios.get('/api/getCategorySon', { params: { parent_id: parentId } }).then(res => { if (res.status === 200) { this.$set(item.child[innerIndex], 'child', res.data.data) } }) } }) }) } } } } </script>