Vue2.x 二次封装双向绑定Selector

目录

项目需求

组件设计


项目需求

1.数据双向绑定

2.支持单选和多选

组件设计

<template>
  <div class="container placeholder_class">
    <el-select v-model="selectedOptions" placeholder="请选择类型" :multiple="multiple" collapse-tags @change="handleChange">
      <el-option v-for="(o, i) in options" :key="i" :value="o.value" :label="o.label"></el-option>
    </el-select>
  </div>
</template>

<script>
export default {
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    value: {
      type: Array,
      default() {
        return []
      }
    },
    multiple: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      options: [],
      //使用v-model无法绑定prop,所以重新创建一个data
      selectedOptions: this.value
    }
  },
  watch: {
    value(newVal) {
      this.selectedOptions = Array.isArray(newVal) ? newVal.join(',') : newVal
    },
    selectedOptions(newVal, oldVal) {
      if (newVal !== oldVal) {
        //将el-selector绑定值传递给当前组件value
        this.$emit('input', Array.isArray(this.newVal) ? this.newVal : [this.newVal])
      }
    }
  },
  created() {
    this.initOptions()
  },
  methods: {
    initOptions() {
      //todo:获取选项
       this.$set(this.$data, 'options', list)
    },
    handleChange(val) {
       //将当前组件绑定值传递给外层组件
      this.$emit('change', Array.isArray(val) ? val : [val])
    }
  }
}
</script>