- A+
所属分类:Web前端
标签组件的效果如下
组件作用
- 这是一个div,包含了两个文本框,后面是添加和删除按钮
- 添加按钮复制出新的div,除了文本框没有内容,其它都上面一样
- 删除按钮将当前行div删除
组件实现
<template> <div> <template v-for="(item,index) in tags"> <el-row :gutter="4" style="margin:5px;"> <el-col :span="8"> <el-input v-model="item.authorName" placeholder="作者名称"/> </el-col> <el-col :span="8"> <el-input v-model="item.authorUnit" placeholder="作者单位名称"/> </el-col> <el-col :span="4"> <el-button type="text" @click="addAuthor">添加</el-button> <span style="padding:2px;">|</span> <el-button type="text" @click="delAuthor(index)">删除</el-button> </el-col> </el-row> </template> </div> </template> <script> export default { name: "AuthorUnit", props: {dic: {type: Array, default: []}}, data() { return { tags: [], }; }, created() { this.tags = this.dic || [];//关键字初始化,dic的值来自于父组件(调用它的组件叫父组件) }, methods: { addAuthor() { this.tags.push({authorName: '', authorUnit: ''}); }, delAuthor(index) { this.tags.splice(index, 1); }, }, } </script>
调用组件,为组件传默认值
<el-form-item label="作者信息" prop="articleAuthorList"> <author-unit v-model="form.articleAuthorList" :dic="form.articleAuthorList"/> </el-form-item>
测试代码
提交之后,将出现当前你添加的这个列表的对象,对接后端接口,将这个数组POST到后端即可,如图所示: