在开发后台管理系统的时候,经常会有搜索表单,可以封装组件,提高开发效率
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>