效果:给select组件传入option请求方法,父组件无需再进行其他操作
<template> <el-select v-model="selectValue" multiple clearable @change="emitChange" value-key="id" placeholder="请选择车辆"> <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id" /> </el-select> </template> <script lang="ts" setup> import { ref, onMounted } from "vue"; const emit = defineEmits(["update:modelValue"]); //接收父组件v-model传递过来的值 const props = defineProps({ modelValue: { type: [String] }, api: { type: Function, required: true } }); //el-select的v-model不能绑定prop属性,所以定义本地变量一个 const selectValue = ref<string[]>([]); //引入修改方法update:modelValue const emitChange = () => { //change事件中需要将这个值传递给更新方法,即update:modelValue emit("update:modelValue", selectValue.value.join(",")); }; //定义数据源,并从服务器获取数据 const options = ref([]); onMounted(async () => { let res = await props.api({}); console.log(res.data); const newData = res.data.map(item => ({ ...item, id: item.id.toString() })); options.value = newData; selectValue.value = props.modelValue ? props.modelValue.split(",") : []; }); </script>
使用:
<MySelect v-model="drawerProps.row!.model" :api="getTableInfoList"></MySelect>
总结: 得不偿失!!!
标签:el,封装,update,props,const,modelValue,select From: https://www.cnblogs.com/easyidea/p/17755365.html