vue~封装一个文本框标签组件

发布时间 2023-09-26 16:46:47作者: 张占岭

用到的技术

  • 父组件向子组件的传值
    类型检查和默认值:您可以为props指定类型检查和默认值。这可以确保传递给子组件的数据符合期望的类型,以及在没有传递数据时具有合理的默认值。例如:
props: {
  message: {
    type: String,
    default: 'Default Message'
  },
  count: {
    type: Number,
    default: 0
  }
}

在上述示例中,message 的默认值是字符串 'Default Message',count 的默认值是数字 0。

标签组件的效果如下

封装代码

<template>
  <div>
    <el-row>
      <el-input
        v-model="inputText"
        type="text"
        @input="checkForSpace"
        @keydown.enter="addTag"
      />
    </el-row>
    <el-row>
      <div class="tags" style="margin-top:5px;">
        <div
          v-for="(tag, index) in tags"
          :key="index"
          class="tag"
        >
          {{ tag }}
          <span class="close" @click="removeTag(index)">&times;</span>
        </div>
      </div>
    </el-row>
  </div>
</template>

<script>
export default {
  name: "InputTag",
  props: {dic: {type: Array, default: []}},
  data() {
    return {
      inputText: '',
      tags: [],
    };
  },created() {
    this.tags = this.dic || [];//关键字初始化,dic的值来自于父组件(调用它的组件叫父组件)
  },
  methods: {
    addTag() {
      if (this.inputText.trim() !== '') {
        this.tags.push(this.inputText);
        this.inputText = '';
      }
    },
    removeTag(index) {
      this.tags.splice(index, 1);
    },
    checkForSpace() {
      if (this.inputText.endsWith(' ')) {
        this.addTag();
      }
    },
  },
};
</script>

<style>
.tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.tag {
  background: #ddd;
  padding: 4px;
  border-radius: 4px;
}

.close {
  margin-left: 4px;
  cursor: pointer;
}
</style>


使用代码

<el-form-item label="文章关键词" prop="kcUsername">
<InputTag v-model="form.keyword" placeholder="文章关系词" :dic="form.keyword" />
</el-form-item>

:dic是子组件里定义的,初始化字典用的,比如在修改信息页面,需要把之前的库里存储的信息加载到关键字标签里,提交表单后,我们的form.keyword将获取你输入的字符串数组。