<template>
  <div class="select-wrapper">
    <div class="result" @click="setOptionsShow">
      {{ data[curentInd - 1].text }}
    </div>
    <div class="options" v-show="optionsShow">
      <div
        class="item"
        v-for="(item, index) of data"
        :key="item.id"
        @click="setOptions(index, item)"
      >
        {{ item.text }}
      </div>
    </div>
  </div>
</template>

<script>
import { reactive, toRefs } from "vue";
export default {
  name: "MySelect",
  props: {
    data: Array,
    curentIndex: {
      type: Number,
      default: 1,
    },
    callback: Function,
  },
  setup(props) {
    const state = reactive({
      optionsShow: false,
      curentInd: props.curentIndex,
    });

    /*
     *控制options显隐
     */
    const setOptionsShow = () => {
      state.optionsShow = !state.optionsShow;
    };

    /*
     *设置options
     */
    const setOptions = (index, item) => {
      props.callback(index + 1, item);
      state.optionsShow = false;
      state.curentInd = index + 1;
    };

    return {
      setOptions,
      setOptionsShow,
      ...toRefs(state),
    };
  },
};
</script>

<style lang="scss" scoped>
.select-wrapper {
  position: relative;
}
.result {
  width: fit-content;
  padding: 6px 15px;
  border: 1px solid #dcdfe6;
  cursor: pointer;
  border-radius: 4px;
}
.result:hover {
  color: gold;
  border: 1px solid gold;
}
.options {
  .item {
    width: fit-content;
    padding: 6px 15px;
  }
  .item:hover {
    color: gold;
  }
}
</style>