elementUI組件封裝(二)------ 標籤

組件代碼

<template>
  <div>
    <el-tag
      :key="tag"
      v-for="tag in dynamicTags"
      closable
      :disable-transitions="false"
      @close="handleClose(tag)"
    >
      {{tag}}
    </el-tag>
    <el-input
      class="input-new-tag"
      v-if="inputVisible && dynamicTags.length<5"
      v-model="inputValue"
      ref="saveTagInput"
      size="small"
      @keyup.enter.native="handleInputConfirm"
      @blur="handleInputConfirm"
      :maxlength="6"
    >
    </el-input>
    <el-button
      v-else-if="dynamicTags.length<5"
      class="button-new-tag"
      size="small"
      @click="showInput"
    >+ New Tag</el-button>
  </div>
</template>
<script>
export default {
  props: { id: { type: Number }, parentTags: { type: String } },
  data() {
    return {
      dynamicTags: [],
      inputVisible: false,
      inputValue: ""
    };
  },
  created() {
    if (this.id == 1) {
      if(this.parentTags){
        this.dynamicTags = this.parentTags.split(" ");
      }else{
        this.dynamicTags = [];
      }
    } else {
      this.dynamicTags = [];
    }
  },
  methods: {
    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
      console.log("closeTags",this.dynamicTags);
      this.$emit("parentTag", this.dynamicTags.join(" "));
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.dynamicTags.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = "";
      console.log("addTags",this.dynamicTags)
      this.$emit("parentTag", this.dynamicTags.join(" "));
    }
  }
};
</script>
<style lang="scss" scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>

使用方式

html

<template>
	<dynamic-tags-vue
          v-if="testShow"
          :id="dataForm.id == 0 ? 0 : 1"
          @parentTag="parentTagFun"
          :parentTags="dataForm.orgTags"
        ></dynamic-tags-vue>
</template>

js

import dynamicTagsVue from "@/components/dynamic-tags/index.vue";
components: {
    dynamicTagsVue
},
data(){
	return {
		testShow:false,
		dataForm:{
			id:0,
			orgTags:""
		}
	}
},
methods(){
	// 標籤組件
    parentTagFun(val) {
      this.dataForm.orgTags = val;
    },
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章