vue-自定义查询组件

在开发后台管理系统的时候,经常会有搜索表单,可以封装组件,提高开发效率在这里插入图片描述
1、封装组件

searchForm组件 👇 自行替换ui组件(饿了么、蚂蚁),写好会用到的类型,v-if判断符合类型则渲染,双向绑定数据

// searchForm组件
<template>
    <div v-for="(item, index) in config" :key="index">
        <div v-if="item.type === 'input'">
            <span>{{item.label}}</span>
            <input type="text" v-model="searchForm[item.prop]" :placeholder="item.placeholder || ''>
        </div>
        <div v-if="item.type === 'textarea'">
            <textarea v-model="searchForm[item.prop]" :placeholder="item.placeholder || ''"></textarea>
        </div>
    </div>
    <button @click="search">查询</button>
</template>

<script>
import { reactive, toRefs } from 'vue'
export default {
    name: 'searchForm',
    emits: ['update:form', 'search'],
    props: {
        form: {
            type: Object,
            default: () => {}
        },
        config: {
            type: Array,
            default: () => []
        }
    },
    setup(props, { emit }) {
        const state = reactive({
            searchForm: JSON.parse(JSON.stringify(props.form)),	// 深拷贝表单对象 不直接修改props
        })
        const bindfn = {
            search() {
                emit('update:form', searchForm)	// 更新数据
                emit('search')	// 触发查询
            }
        }
        return {
            ...toRefs(state),
            ...bindfn
        }
    }
}
</script>
2、使用组件

定义好form、config传给组件

<template>
  <search-form v-model:form="form" :config="config" @search="search"></search-form>
</template>

<script>
import { reactive, toRefs } from 'vue'
import searchForm from './searchForm.vue'
export default {
  name: 'HelloWorld',
  components: {
    searchForm
  },
  setup() {
    const state = reactive({
      form: {
        type: '',
        text: 1
      },
      config: [
        {
          type: 'input',  // 定义类型
          prop: 'type',   // 字段
          label: '类型',  // label
          placeholder: '请输入'
        },
        {
          type: 'textarea',
          prop: 'text',
          label: '文本域',
        }
      ]
    })
    const bindfn = {
      search() {
        console.log(state.form);  // 监听查询
      }
    }

    return {
      ...toRefs(state),
      ...bindfn
    }
  }
}
</script>
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值