ElementUI Tag功能实现多标签生成
做项目过程中需要通过选择内容实现Tag多标签功能,效果如下:
ElementUi官方给出的的示例:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <el-tag 2 :key="tag" 3 v-for="tag in dynamicTags" 4 closable 5 :disable-transitions="false" 6 @close="handleClose(tag)"> 7 {{tag}} 8 </el-tag> 9 <el-input 10 class="input-new-tag" 11 v-if="inputVisible" 12 v-model="inputValue" 13 ref="saveTagInput" 14 size="small" 15 @keyup.enter.native="handleInputConfirm" 16 @blur="handleInputConfirm" 17 > 18 </el-input> 19 <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button> 20 21 <style> 22 .el-tag + .el-tag { 23 margin-left: 10px; 24 } 25 .button-new-tag { 26 margin-left: 10px; 27 height: 32px; 28 line-height: 30px; 29 padding-top: 0; 30 padding-bottom: 0; 31 } 32 .input-new-tag { 33 width: 90px; 34 margin-left: 10px; 35 vertical-align: bottom; 36 } 37 </style> 38 39 <script> 40 export default { 41 data() { 42 return { 43 dynamicTags: ['标签一', '标签二', '标签三'], 44 inputVisible: false, 45 inputValue: '' 46 }; 47 }, 48 methods: { 49 handleClose(tag) { 50 this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1); 51 }, 52 53 showInput() { 54 this.inputVisible = true; 55 this.$nextTick(_ => { 56 this.$refs.saveTagInput.$refs.input.focus(); 57 }); 58 }, 59 60 handleInputConfirm() { 61 let inputValue = this.inputValue; 62 if (inputValue) { 63 this.dynamicTags.push(inputValue); 64 } 65 this.inputVisible = false; 66 this.inputValue = ''; 67 } 68 } 69 } 70 </script>
但是实际项目中Tag显示的内容是需要弹框选择的,代码如下:
1 <div class="formTime"> 2 <el-tag 3 :key="tag" 4 v-for="tag in dynamicTags" 5 closable 6 :disable-transitions="false" 7 @close="handleClose(tag)"> 8 {{tag}} 9 </el-tag> 10 <el-dialog 11 width="30%" 12 append-to-body 13 :visible.sync="inputVisible"> 14 <el-time-picker 15 is-range 16 v-model="tagTime" 17 format="HH:mm:ss" 18 value-format="HH:mm:ss" 19 range-separator="至" 20 start-placeholder="开始时间" 21 end-placeholder="结束时间" 22 placeholder="选择时间范围"> 23 </el-time-picker> 24 <span slot="footer" class="dialog-footer"> 25 <el-button @click="inputVisible = false">取 消</el-button> 26 <el-button type="primary" @click="tagTimeClick(tagTime)">确 定</el-button> 27 </span> 28 </el-dialog> 29 30 </el-input> 31 <el-button class="button-new-tag" size="small" @click="showInput" icon="el-icon-plus"/> 32 </div>
data中加入:
1 dynamicTags: [], 2 inputVisible: false, 3 inputValue: "", 4 tagTime: [new Date(), new Date()]
methods方法中代码如下:
1 handleClose(tag) { 2 this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1); 3 }, 4 showInput() { 5 this.inputVisible = true; 6 }, 7 tagTimeClick(tagTime) { 8 console.log(tagTime, "tegTime"); 9 let inputValue = tagTime[0] + "-" + tagTime[1]; 10 console.log(inputValue); 11 if (inputValue) { 12 this.dynamicTags.push(inputValue); 13 } 14 this.inputVisible = false; 15 },
共勉:“人生如果错了方向,停止就是进步”