目录
该组件实现了一个标签页的添加和删除功能
组件属性介绍:
- <el-tag> 标签渲染了用于展示标签页标签的元素
- <el-input> 标签渲染了用于输入新标签页名称的元素
- <el-button> 标签渲染了一个显示“+ New Tag”文本的按钮。具体功能如下:
:key="tag" 用于渲染每个标签页的key值;
v-for="tag in dynamicTags" 用于渲染动态标签数组 dynamicTags 中的每个标签页;
closable 用于使每个标签页展示一个关闭按钮;
:disable-transitions="false" 用于启用动画特效;
@close="handleClose(tag)" 用于删除某个标签页,触发 handleClose 方法;
v-if="inputVisible" 用于使 <el-input> 元素在条件为真时显示;
v-model="inputValue" 将输入框内的值与 inputValue 数据绑定;
ref="saveTagInput" 用于在组件中引用该输入框,方便后续将输入框聚焦;
size="small" 定义了输入框的大小;
@keyup.enter.native="handleInputConfirm" 监听输入框的回车事件,触发 handleInputConfirm 方法;
@blur="handleInputConfirm" 监听输入框失去焦点事件
<el-tag :key="tag" v-for="tag in dynamicTags" closable :disable-transitions="false" @close="handleClose(tag)"> {{tag}} </el-tag> <el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm" > </el-input> <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button> <style> .el-tag + .el-tag { margin-left: 10px; } .button-new-tag { margin-left: 10px; height: 32px; line-height: 30px; padding-top: 0; padding-bottom: 0; } .input-new-tag { width: 90px; margin-left: 10px; vertical-align: bottom; } </style> <script> export default { data() { return { dynamicTags: ['标签一', '标签二', '标签三'], inputVisible: false, inputValue: '' }; }, methods: { handleClose(tag) { this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1); }, showInput() { this.inputVisible = true; this.$nextTick(_ => { this.$refs.saveTagInput.$refs.input.focus(); }); }, handleInputConfirm() { let inputValue = this.inputValue; if (inputValue) { this.dynamicTags.push(inputValue); } this.inputVisible = false; this.inputValue = ''; } } } </script>
将所有标签在同一个数据字段中发送给后端
可以将 dynamicTags 数组绑定到一个 form 数据对象中, 以表单提交的方式发送给后端。
例如,在 data中新增属性 form, 并将 dynamicTags 绑定到 form.tags 上:
data() { return { dynamicTags: ['标签一', '标签二', '标签三'], inputVisible: false, inputValue: '', form: { tags: [] // 添加一个 tags 数组属性,用于存放标签页数据 } } }
接下来在 handleClose 和 handleInputConfirm 方法中,
每次修改 dynamicTags 数组时,同时也要更新到 form.tags 数组中:
methods: { handleClose(tag) { const index = this.dynamicTags.indexOf(tag) if (index > -1) { this.dynamicTags.splice(index, 1) this.form.tags.splice(index, 1) // 更新 form.tags } }, handleInputConfirm() { let inputValue = this.inputValue if (inputValue && this.dynamicTags.indexOf(inputValue) === -1) { this.dynamicTags.push(inputValue) this.form.tags.push(inputValue) // 更新 form.tags } this.inputVisible = false this.inputValue = '' } }