new Vue({ el: '#app', data: { newTag: '', //tags: ['Vue', 'React', 'Jquery'] tags: [] }, methods: { add(tag) { if (tag && this.tags.indexOf(tag) === -1) { this.tags.push(tag) } this.newTag = '' }, del(index) { this.tags.splice(index, 1) }, delLastTag() { if (this.newTag) { return } this.tags.pop() } } });
<div id="app"> <div class="tags-wrap"> <div class="tags"> <span class="content" v-for="(tag, index) in tags" :key="index">{{tag}} <span class="del" @click="del(index)">×</span> </span> <input class="tags-input" type="text" v-model="newTag" v-on:keyup.delete.stop="delLastTag()" v-on:keyup.enter="add(newTag)" placeholder="click enter"> </div> </div> <br> <div class="form-group"> <label for="">Tags:</label> <code>{{tags}}</code> </div> </div>
.tags-wrap { background-color: #fff; border: 1px solid #ccc; overflow: hidden; padding-left: 4px; padding-top: 4px; cursor: text; text-align: left; -webkit-appearance: textfield; } .tags-wrap::after { content: ""; display: block; height: 0; clear: both; } .tags-input { background: transparent; border: 0; color: #777; font-size: 13px; font-weight: 400; margin-bottom: 6px; margin-top: 1px; outline: none; padding: 4px; padding-left: 0; width: 80px } .content { background-color: #e0e0e0; border-radius: 8px; color: rgba(0, 0, 0, .87); line-height: 25px; display: inline-block; font-size: 14px; font-weight: 400; margin-bottom: 4px; margin-right: 4px; padding: 6px; } .del { cursor: pointer; font-weight: 700; color: #1F1F1F; }