<template>
  <el-form-item label="标签">
    <el-input
      v-model="inputValue"
      placeholder="请输入内容"
      @keyup.enter="handleAddTag"
    ></el-input>
    <el-button @click="handleAddTag">+</el-button>
    <el-tag
      v-for="(tag, index) in dynamicTags"
      :key="index"
      closable
      :disable-transitions="false"
      @close="handleClose(tag)">
      {{ tag }}
    </el-tag>
  </el-form-item>
</template>
 
<script>
export default {
  data() {
    return {
      dynamicTags: [],
      inputValue: '',
    };
  },
  methods: {
    handleAddTag() {
      const inputValue = this.inputValue.trim();
      if (!inputValue) {
        return;
      }
      this.dynamicTags.push(inputValue);
      this.inputValue = '';
    },
    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
    },
  },
  mounted() {
    // 假设从后端获取到的标签数据为字符串,如"Vue,React,Angular"
    const backendTags = "Vue,React,Angular";
    this.dynamicTags = backendTags.split(',');
  }
};
</script>这个代码实例展示了如何在Vue 3中实现一个用户可以添加和移除标签的功能。它使用了el-input来输入文本,el-button来触发添加操作,并且使用了el-tag组件来展示已经添加的标签。数据以逗号分隔的字符串形式传递给后端,并在组件挂载时(mounted钩子)从后端获取数据并解析回显到界面上。