----TagsInput组件封装----
首先展示一下实现效果:
直接上代码:
1.html:
1 <template> 2 <div class="input tags-wrap"> 3 <div 4 class="tags" 5 transition="tags" 6 :style="{backgroundColor: bgc[item.bgc_no]}" 7 v-for="(item,index) in dis_source" 8 :key="index" 9 > 10 <span class="content">{{item.text}}</span> 11 <span class="del" @click="del(index, false)">×</span> 12 </div> 13 <input 14 class="tags-input" 15 type="text" 16 placeholder="标签,按 enter 创建" 17 v-model="text" 18 @keyup.enter="add(text)" 19 @keydown.delete="del(source.length - 1, true)" 20 /> 21 </div> 22 </template>
2.js:
<script> export default { props: { source: { type: Array, default: () => { return [] } } }, watch: { source: { handler(newValue) { var dis_source = [] this.source.forEach((item, index) => { var obj = { text: item, bgc_no: Math.ceil(Math.random() * 10) - 1 } dis_source.push(obj) }) this.dis_source = dis_source } } }, data() { return { text: '', bgc: [ '#e961b4', '#ed664b', '#7b6ac7', '#56abd1', '#f7af4c', '#fe5467', '#52c7bd', '#a479b7', '#cb81ce', '#5eabc5' ], dis_source: [] } }, methods: { add(text) { if (text !== '') { var count = this.source.length this.$set(this.source, count, text) this.$set(this.dis_source, count, { text: text, bgc_no: Math.ceil(Math.random() * 10) - 1 }) this.text = '' } }, del(index, way) { if (way) { if (index >= 0 && this.text === '') { this.source.splice(index, 1) this.dis_source.splice(index, 1) } } else { this.source.splice(index, 1) this.dis_source.splice(index, 1) } } } } </script>
3.css:
<style lang="scss"> //输入框tags .tags-wrap { width: 500px; height: 100%; outline: none; border: 1px solid #dcdfe6; border-radius: 4px; &::after { content: ""; display: block; height: 0; clear: both; } } .tags, .tags-input { position: relative; float: left; color: #fff; line-height: 28px; margin: 4px; padding: 0 22px 0 10px; border-radius: 4px; .content { line-height: 28px; } .del { width: 22px; height: 28px; text-align: center; cursor: pointer; position: absolute; top: -1px; right: 0; } } .tags-input { font-size: 14px; padding: 0; background-color: inherit; border: none; color: inherit; width: 10em; outline: none; } </style>