ElementUI 之 Cascader 級聯選擇器指定 value label


 

  ElementUI 的 Cascader 級聯選擇器個人覺得很好用,但是對 :options="options" 里的數據格式是有特定要求的:input 框顯示的值是 options 里的 label 值。如果 options 的鍵值對不是 value label ,就需要 props 來配置。

 

如何配置 value label?

<el-cascader
    v-model="data"
    :options="options"
    placeholder="請選擇" :props="{ value: 'id', label: 'name'}"
    @change="handlechange">
</el-cascader>

js:
export default {
  data() {
    options:[
      { id: 1, name: '第一層', children: [ id: 11, name: '水果']},
      { id: 2, name: '第二層', children: [ id: 22, name: '蔬菜'] },
    ]
  }
}

 

頁面顯示:

  第一層/水果

  or

  第二層/蔬菜

 

注意 @change 事件:如果選擇的是 “第一層/水果”,console.log(value) 輸出的值為 [1, 11]。

所以,如果需要拿到數據反顯內容的需求,則需要后台返回 value 的數組,賦值給 v-model 的 data。

handlechange (value) {
    console.log(value) // 這里的值會輸出 value 的一個數組
}

 

  講兩個遇到的坑:

  1、自定義節點時,可能會遇到這樣的寫法:slot-scope="{ node, data }" 這種寫法在 IE 中會報錯,詳情及解決方法見另一篇博文 Vue IE11 報錯 Failed to generate render function:SyntaxError: 缺少標識符 in

<el-cascader :options="options">
  <template slot-scope="{ node, data }">
    <span>{{ data.label }}</span>
    <span> ({{ data.children.length }}) </span>
  </template>
</el-cascader>

 

  2、不要天真的在 <template> 下的標簽上綁定 click 等事件,因為頁面渲染出來的元素(比如上段代碼中的 <span>),占位面積不是一整行,如果你點擊的是綠色箭頭部分,是沒有獲取到它的 value 值,所以最好按照官方文檔推薦的寫法,在 <el-cascader> 上綁定 change。當然可以調 <span> 的樣式,但是太過於麻煩。

    

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM