美文网首页
v-model 配合 computed对表单进行封装

v-model 配合 computed对表单进行封装

作者: zhao_madman | 来源:发表于2023-04-07 12:50 被阅读0次
    父组件
    <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;
    

    相关文章

      网友评论

          本文标题:v-model 配合 computed对表单进行封装

          本文链接:https://www.haomeiwen.com/subject/kpvpddtx.html