系统中的el-editor,el-file-upload,el-file-select,el-field等组件都是封装好的,那么我们该如何定义自己需要的组件呢?
比如以下问题:我选择学校,加载出这个学校的专业,选择专业加载出这个专业的系别
1.在当前页面,自定义组件
<script>
/**
* 自定义组件
*/
Vue.component('el-form-select', {
template:`
<el-form
ref="form"
class="el-form-select"
label-width="120px"
:rules="rules">
<el-form-item label="学校:" prop="school">
<el-select v-model="form.school" @change="formChange(1)">
<el-option
v-for="(item, index) in schoolList"
v-if="item.pid == 0"
:key="index"
:value="item.id"
:label="item.title">
</el-option>
</el-select>
</el-form-item>
<el-form-item label="专业:" prop="major">
<el-select v-model="form.major" @change="formChange(2)">
<el-option
v-for="(item, index) in schoolList"
v-if="item.pid == form.school"
:key="index"
:value="item.id"
:label="item.title">
</el-option>
</el-select>
</el-form-item>
<el-form-item label="系别:" prop="pedigree">
<el-select v-model="form.pedigree" @change="formChange(3)">
<el-option
v-for="(item, index) in schoolList"
v-if="item.pid == form.major"
:key="index"
:value="item.id"
:label="item.title">
</el-option>
</el-select>
</el-form-item>
</el-form>
`,
props: {
value: {
type: Object,
default: {
school: '',
major: '',
pedigree: '',
},
},
},
data() {
return {
form: this.value,
rules: {},
schoolList: [
{id: 1, pid: 0, title: '杭州师范大学'},
{id: 2, pid: 0, title: '杭州工业大学'},
{id: 3, pid: 0, title: '杭州医药大学'},
{id: 4, pid: 1, title: '历史知识'},
{id: 5, pid: 2, title: '软件开发'},
{id: 6, pid: 3, title: '普通外科'},
{id: 7, pid: 4, title: '文学系'},
{id: 8, pid: 5, title: '工程系'},
{id: 9, pid: 6, title: '医学系'},
{id: 10, pid: 1, title: '商务电子'},
{id: 11, pid: 2, title: '物联网'},
{id: 12, pid: 3, title: '医学器械'},
{id: 13, pid: 10, title: '外贸系'},
{id: 14, pid: 11, title: '人工智能'},
{id: 15, pid: 12, title: '设备检修'},
],
}
},
methods: {
// 每次表单发送变化,则值返回
formChange(level) {
// 当1级发送改变,23级数据清空
if (level == 1) {
this.form = Object.assign({}, this.form, {major: '', pedigree: ''});
}
// 当2级发送改变,3级数据清空
if (level == 2) {
this.form = Object.assign({}, this.form, {pedigree: ''});
}
this.$emit('input', this.form);
},
}
})
</script>
2.在当前页面,field参数中引入组件
{
prop: 'xxx',
label: '', // 这里为空,是因为自定义的表单组件有标题
table: false,
form: {
is: 'el-form-select', // 引入自定义表单的名称
labelWidth: '0px', // 这里为0,是因为自定义的表单组件有标题
default: {school: '', major: '', pedigree: ''}, // 默认参数
},
},