tags.vue 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <template>
  2. <div class="container">
  3. <el-tag size="medium" :key="tag" v-for="tag in dynamicTags" closable :disable-transitions="false" @close="handleClose(tag)">
  4. {{ tag }}
  5. </el-tag>
  6. <el-input
  7. class="input-new-tag"
  8. v-if="inputVisible"
  9. v-model="inputValue"
  10. ref="saveTagInput"
  11. size="mini"
  12. @keyup.enter.native="handleInputConfirm"
  13. @blur="handleInputConfirm"
  14. >
  15. </el-input>
  16. <el-button v-else class="button-new-tag" size="mini" @click="showInput">+ {{ addText }}</el-button>
  17. </div>
  18. </template>
  19. <script>
  20. export default {
  21. model: {
  22. prop: 'value',
  23. event: 'change', // 默认为input时间,此处改为change
  24. },
  25. props: {
  26. value: { type: Array, required: false, default: () => [] },
  27. addText: { type: String, required: false, default: '添加' },
  28. },
  29. data() {
  30. return {
  31. dynamicTags: [...this.value],
  32. inputVisible: false,
  33. inputValue: '',
  34. };
  35. },
  36. methods: {
  37. handleClose(tag) {
  38. this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
  39. this.$emit('change', this.dynamicTags);
  40. },
  41. showInput() {
  42. this.inputVisible = true;
  43. this.$nextTick(_ => {
  44. this.$refs.saveTagInput.$refs.input.focus();
  45. });
  46. },
  47. handleInputConfirm() {
  48. let inputValue = this.inputValue;
  49. if (inputValue && !this.dynamicTags.includes(inputValue)) {
  50. this.dynamicTags.push(inputValue);
  51. this.$emit('change', this.dynamicTags);
  52. }
  53. this.inputVisible = false;
  54. this.inputValue = '';
  55. },
  56. },
  57. };
  58. </script>
  59. <style lang="less" scoped>
  60. .container {
  61. display: flex;
  62. flex-wrap: wrap;
  63. }
  64. //.el-tag + .el-tag {
  65. .el-tag {
  66. margin-right: 10px;
  67. margin-bottom: 10px;
  68. }
  69. .button-new-tag {
  70. height: 28px;
  71. line-height: 26px;
  72. padding-top: 0;
  73. padding-bottom: 0;
  74. }
  75. .input-new-tag {
  76. width: 90px;
  77. margin-left: 10px;
  78. vertical-align: bottom;
  79. }
  80. </style>