ElementUI下拉組件el-select一次從后端獲取選項并設置默認值方式
ElementUI el-select一次從后端獲取選項并設置默認值
使用ElementUI下拉框組件el-select時遇到一個問題,期望從后端獲取選項并設置默認值,其中選項的label為名稱,value為id,但是默認值顯示出來的是value而非label。
前端代碼大致如下:
<el-select style="width: 130px" v-model="extraAttr.value_id" placeholder="請選擇屬性值" @change="handleSelectAttrValue(extraAttr)" @clear="handleClearAttrValue(extraAttr)" filterable clearable> ? ? <el-option v-for="(item, index5) in getValues(extraAttr.attribute_id)" :key="index5" :label="item.value" :value="item.value_id"></el-option> ?</el-select>
computed: {
? ? // 按屬性id獲取屬性取值選項
? ? getValues() {
? ? ? ? return function (index) {
? ? ? ? ? ? let nullValues = [];
? ? ? ? ? ? if (this.attrValueMap.has(index)) {
? ? ? ? ? ? ? ? return this.attrValueMap.get(index);
? ? ? ? ? ? }
? ? ? ? ? ? return nullValues;
? ? ? ? }
? ? },
? ? ...
}其中,el-select綁定屬性值id,在created階段通過post請求去后端請求所有屬性及屬性值的信息并緩存到attrValueMap(因為嵌套了三層循環(huán)…每一層選擇一個值就要同步更改下拉選項),然后在編輯頁就有了默認值;el-option通過給computed計算屬性傳參從attrValueMap中用屬性id獲取屬性值數(shù)組。
我的解決方案
給el-select動態(tài)綁定disabled屬性
這里我的理解是
value_id、傳遞給計算屬性的參數(shù)attribute_id和attrValueMap都不變,所以并不能觸發(fā)重新渲染,那只能更改其他地方去觸發(fā)重新渲染。
<el-select style="width: 130px" v-model="extraAttr.value_id" placeholder="請選擇屬性值" @change="handleSelectAttrValue(extraAttr)" @clear="handleClearAttrValue(extraAttr)" filterable clearable :disabled="isAttributeDisabled"> ? ? <el-option v-for="(item, index5) in getValues(extraAttr.attribute_id)" :key="index5" :label="item.value" :value="item.value_id"></el-option> </el-select>
通過:disabled="isAttributeDisabled"綁定isAttributeDisabled,初始時設置為true,在created階段post請求結(jié)束時更新為false,這樣就會觸發(fā)重新渲染el-select組件
ElementUI Select設置默認值更改選擇后值不改變
使用 ElementUI 的 Select 選擇器選擇了其他選擇值,框內(nèi)的值沒有改變,還是顯示原來的值,但是綁定的id值變了
解決方案:在選擇器的值發(fā)生改變時刷新選擇器組件:@change=“$forceUpdate()”
<el-select ? v-model="Value" ? placeholder="請選擇" ? @change="$forceUpdate()" > ? <el-option ? ? v-for="item in List" ? ? :key="item.id" ? ? :label="item.name" ? ? :value="item.id" ? /> </el-select>
注意:
我查找了下綁定值沒變的原因是因為我綁定的value值在data中沒有定義才會出現(xiàn)這種問題,如果綁定的是對象的話,比如綁定的是obj.value,并且data中已經(jīng)定義了,還出現(xiàn)了綁定值不變的情況,說明在代碼編輯的過程中把obj重新賦值了,賦的值中沒有value屬性,也就是說把value屬性給干掉了,所以會出現(xiàn)綁定值不變的情況,所以要做的就是在代碼中把value屬性加上就可以了。
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
setup+ref+reactive實現(xiàn)vue3響應式功能
這篇文章介紹了通過setup+ref+reactive實現(xiàn)vue3響應式功能,文中通過示例代碼介紹的非常詳細。對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-11-11

