组件封装–搜索表单 searchForm.vue
可根据需要,参考姓名和工作自行增加更多常用的默认搜索项
<template> <div style="padding: 30px; width: 300px"> <el-form ref="searchFormRef" :model="searchData" :label-width="searchOption.labelWidth || '80px'" :size="searchOption.size || 'mini'" > <el-form-item v-if="searchOption.name" label="姓名" prop="name" :rules="{ required: true, message: '不能为空' }" > <el-input v-model="searchData.name"></el-input> </el-form-item> <SearchJob v-if="searchOption.job" :searchData="searchData" /> <slot> </slot> <el-form-item> <el-button type="primary" @click="search">搜索</el-button> <el-button type="primary" @click="reset">重置</el-button> </el-form-item> </el-form> </div> </template> <script> import SearchJob from "./search_job.vue"; export default { components: { SearchJob, }, props: { searchData: Object, searchOption: Object, }, methods: { search() { this.$refs.searchFormRef.validate((valid) => { if (valid) { alert("通过表单校验,开始搜索!"); } }); }, reset() { this.$emit("reset"); }, }, }; </script>
内嵌组件 search_job.vue
具体原理可参考
https://blog.csdn.net/weixin_41192489/article/details/127966234
<template> <el-form-item label="工作" prop="job" :rules="{ required: true, message: '不能为空' }" > <el-input v-model="searchData.job"></el-input> </el-form-item> </template> <script> export default { props: { searchData: Object, }, }; </script>
使用方法 index.vue
- 可直接在 SearchForm 内部通过默认插槽添加更多搜索项
- 必要变量有 searchData 和 searchOption
- 必要方法有 reset
<template> <div style="padding: 30px; width: 300px"> <SearchForm :searchData="searchData" :searchOption="searchOption" @reset="reset" > <el-form-item label="爱好" prop="hobby" :rules="{ required: true, message: '不能为空' }" > <el-input v-model="searchData.hobby"></el-input> </el-form-item> </SearchForm> </div> </template> <script> import SearchForm from "./searchForm.vue"; export default { components: { SearchForm, }, data() { return { searchData: {}, // 搜索表单的配置--是否显示默认搜索项 searchOption: { labelWidth: "100px", size: "small", name: true, job: true, }, }; }, methods: { reset() { this.searchData = {}; }, }, }; </script>