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> 的样式,但是太过于麻烦。

    

原文地址:https://www.cnblogs.com/zhangym118/p/11369259.html