Vue 二次封装 Element-UI Select 组件


在这里插入图片描述

子组件示例代码

<template>
  <div>
    <el-select
      v-model="childValue"
      placeholder="请选择"
      filterable
      @change="onChange"
    >
      <el-option
        v-for="item in options"
        :key="getKey(item.id)"
        :label="item.name"
        :value="item.id"
      >
      </el-option>
    </el-select>
    <!-- <div>
      <slot :user="options"></slot>
    </div> -->
  </div>
</template>

<script>
export default {
  name: "",
  props: {
    // props是父组件传过来的值
    parentValue: null,
    url: null,
  },
  data() {
    return {
      childValue: this.parentValue,
      options: [],
    };
  },
  methods: {
    getKey(key) {
      return Symbol(key);
    },
    onChange() {},
    getData() {
      this.options = [
        { id: "10001", name: "菜狗" },
        { id: "10002", name: "黑骑天使" },
        { id: "10003", name: "六神盾" },
      ];
    },
  },
  mounted() {
    this.getData();
  },
  watch: {
    parentValue(val) {
      this.childValue = val;
    },
    childValue(val) {
      this.$emit("input", val); // 实现父子组件间的值传递 this.$emit(事件,值)  (这里的input:v-model是一个语法糖,等于:value+@input)
    },
  },
};
</script>

<style scoped lang='scss'>
</style>

父组件调用封装的子组件

<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png" width="25%" />
    <ChildSelect v-model="selectId" />
    <el-button type="primary" @click="getVal">获取选择id</el-button>
    <p>{{ selectVal }}</p>
  </div>
</template>

<script>
import ChildSelect from "./components/ChildSelect";

export default {
  name: "App",
  components: {
    ChildSelect,
  },
  data() {
    return {
      selectId: "",
      selectVal: "",
    };
  },
  methods: {
    getVal() {
      this.selectVal = this.selectId;
    },
  },
};
</script>

<style>
#app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

源码地址
https://codesandbox.io/s/focused-ardinghelli-trzkp?file=/src/App.vue:0-763

Logo

前往低代码交流专区

更多推荐