Vue 自定义标签输入框组件

发布时间:2023年12月28日

组代代码

<template>
  <div class="tags_input flex flex-center-cz flex-wrap border-box padding-bottom-s full-width ">
    <div v-for="item in list" class="items margin-left-s padding-left-s padding-right-s margin-top-s  flex flex-center-cz  ">
      <div>{{ item }}</div>
      <img src="@/assets/images/icon/guanbi.png" class="logo-15 pointer" @click="close(item)" />
    </div>
    <input type="text" :placeholder="placeholder" v-model="value" @keyup.enter="add"  class="margin-left-s margin-top-s " style="width: 120px;" />
  </div>
</template>
<script>
export default {
  name: 'TagsInput',
  props: {
    listFilter: Boolean, // 是否去重
    values: {},  // 默认值
    placeholder: null // 占位文字
  },
  model: {
    prop: "values",
    event: "change"
  },
  created() {
  },
  data() {
    return {
      value: '',
      list: [],
    }
  },
  mounted() {
    if (this.values != null && this.values != "") {
      this.list = this.values.split(",")
    } else {
      this.list = [];
    }
  },
  methods: {
    close(value) {
      this.list = this.list.filter(item => item !== value);//数组过滤得到一个匹配的一个新数组
      this.$emit("change", this.list.join(",") );//触发父组件 change事件
    },
    add() {
      console.log("this.list=========", this.list)
      console.log("this.value=======", this.value)
      let self = this
      if (self.value !== '' || self.value !== ' ') {
        console.log("value", self.value)
        console.log("list", self.list)
        self.list.push(self.value)
        if (self.listFilter) {
          let arr = self.list
          let set = new Set(arr)
          self.list = Array.from(set)
        }
      }
      self.value = ''
      console.log("list=======23", self.list)
      self.$emit('change', self.list.join(","))
    },
  }
}
</script>
<style scoped>
.tags_input {
  border: 1px solid #E1DCDC;
  background-color: #FFFFFF;
}

.tags_input input {
  border: 0;
  width: 100%
}


.tags_input .items {
  height: 26px;
  border-radius: 2px;
  border: 1px solid rgba(0, 0, 0, .2);
}
</style>

组件使用代码

<template>
  <div class="root flex flex-col border-box padding-l">
    <TagInput v-model="tags" style="width: 300px;"></TagInput>
  </div>
</template>

<script>
import TagInput from '@/components/input/TagInput.vue'

export default{
  name:'',
  created() {
  },
  components: {TagInput},
  data() {
    return {
      tags:null
    }
  },
  methods:{
  }
}
</script>

文章来源:https://blog.csdn.net/gdgztt/article/details/135257521
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。