父组件
<template>
<SearchBar v-model="modelValue"/>
</template>
<script setup>
import SearchBar from "@/components/SearchBar.vue";
import { ref } from "vue";
const modelValue = ref({
keyword: "",
placeholder: "请输入你要查询的关键字",
options: [
{ label: "视频", value: "video" },
{ label: "语音", value: "audio" },
{ label: "用户", value: "user" },
],
selectValue: "audio",
});
</script>
子组件
<template>
<el-input
v-model="model.keyword"
:placeholder="model.placeholder"
class="input-with-select"
>
<template #prepend>
<el-select
v-model="model.selectValue"
placeholder="Select"
style="width: 115px"
>
<el-option
v-for="item in model.options"
:key="item.value"
:label="item.label"
:value="item.value"
/>
</el-select>
</template>
<template #append>
<el-button :icon="Search" />
</template>
</el-input>
</template>
<script setup>
import { Search } from "@element-plus/icons-vue";
import useVModel from '@/utils/useVModel';
const emit = defineEmits(['update:modelValue']);
const props = defineProps({
modelValue: {
type: Object,
required: true,
},
});
const model = useVModel(props,'modelValue',emit)
</script>
useVModel方法
import {computed } from 'vue';
const useVModel = (props, propsName, emit) => {
return computed({
get() {
return new Proxy(props[propsName], {
set(obj, name, val) {
emit('update:' + propsName, {
...obj,
[name]: val
})
return true;
}
})
}
})
}
export default useVModel;