最近在做一個後臺管理相關的東西,有一個關於下拉框聯動的小技巧可以分享給大家,寫好後不用更改前端程式碼,只需更改後端相應的配置,即可增加相對應的聯動。
比如有兩個下拉框一個省和一個市的下拉框,這裡只是拿省市打個比方,兩個元素是相互依賴的關係,方便理解,並不是要做省市區的三級聯動,當然也可以做。
1 使用者模型定義相關引數
class User
{
const PROVINCE_BEIJING = 'geijing';
const PROVINCE_SHANGHAI = 'shanghai';
public static $provinceMaps = [
self::PROVINCE_BEIJING=>'北京',
self::PROVINCE_SHANGHAI=>'上海'
];
const CITY_DONGCHENG='dongcheng';
const CITY_ZHAOYANG='zhaoyang';
const CITY_PUDONG='pudong';
const CITY_BAOSHAN='baoshan';
public static $cityMaps=[
self::CITY_DONGCHENG=>'東城區',
self::CITY_ZHAOYANG=>'朝陽區',
self::CITY_PUDONG=>'浦東新區',
self::CITY_BAOSHAN=>'寶山區',
];
//省市聯動配置
public static $cityByProvinceMaps=[
self::PROVINCE_BEIJING=>[
self::CITY_DONGCHENG=>'東城區',
self::CITY_ZHAOYANG=>'朝陽區',
],
self::PROVINCE_SHANGHAI=>[
self::CITY_PUDONG=>'浦東新區',
self::CITY_BAOSHAN=>'寶山區'
]
];
}
2 獲取定義的引數
獲取方法
function getMModelMaps($classes)
{
$map = [];
foreach ($classes as $class){
$ref = new \ReflectionClass($class);
$className = $ref->getShortName();
$constants = $ref->getConstants();
$staticProperties = $ref->getStaticProperties();
$onlyMapsProperties = [];
foreach ($staticProperties as $key=>$v){
if(strpos($key,'Maps') !== false){
$onlyMapsProperties[$key] = $v;
}
}
$map[$className]= array_merge($constants,$onlyMapsProperties);
}
return $map;
}
$maps= getMModelMaps([User::class]);
執行轉化為json
的結果
{
"User": {
"PROVINCE_BEIJING": "beijing",
"PROVINCE_SHANGHAI": "shanghai",
"CITY_DONGCHENG": "dongcheng",
"CITY_ZHAOYANG": "zhaoyang",
"CITY_PUDONG": "pudong",
"CITY_BAOSHAN": "baoshan",
"provinceMaps": {
"beijing": "北京",
"shanghai": "上海"
},
"cityMaps": {
"dongcheng": "東城區",
"zhaoyang": "朝陽區",
"pudong": "浦東新區",
"baoshan": "寶山區"
},
"cityByProvinceMaps": {
"beijing": {
"dongcheng": "東城區",
"zhaoyang": "朝陽區"
},
"shanghai": {
"pudong": "浦東新區",
"baoshan": "寶山區"
}
}
}
}
3 傳到前端展示
使用的是laravel
的 blade
模版
<div id="app">
<select name="" v-model="province">
<option value="">請選擇省</option>
<option v-for="(name,key) in provinceMaps" :value="key">@{{name}}</option>
</select>
<select v-model="city">
<option value="">請選擇市</option>
<option v-for="(name,key) in cityMaps" :value="key">@{{name}}</option>
</select>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
var app = new Vue({
el: '#app',
data: {
province:'',
city:'',
maps:@json($maps),
provinceMaps:@json($maps).User.provinceMaps,
cityMaps:@json($maps).User.cityMaps,
},
watch:{
province(val){
this.city=''
this.cityMaps=this.maps.User.cityByProvinceMaps[val]
},
city(val){
if(val){
if(!this.province){
this.city=''
alert('請先選擇省')
}
}
}
}
})
</script>
4 增加聯動配置
比如想增加個天津的配置
在User
增加配置即可,不用更改前端程式碼
本作品採用《CC 協議》,轉載必須註明作者和本文連結