欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

element中动态编辑标签+带输入建议

程序员文章站 2022-06-07 15:38:27
...

直接按照正常思路整合两个组件,会出bug.可能是操作ref(即dom操作)的原因

                    <!-- 标签 -->
                    <el-tag :key="tag" v-for="tag in dynamicTags" closable :disable-transitions="false"
                      @close="handleClose(tag)">
                      {{tag}}
                    </el-tag>

                    <el-autocomplete class="inline-input" v-model="inputValue" :fetch-suggestions="querySearch"
                      placeholder="请输入内容" @select="handleSelect" @keyup.enter.native="handleInputConfirm"
                      @blur="handleInputConfirm"></el-autocomplete>

                    <el-button class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>
<script>
export default {
  data() {
    return {
      dynamicTags: ['标签一', '标签二', '标签三'],
      inputVisible: false,
      inputValue: '',

      restaurants: [],
      state1: '',
      state2: ''
    }
  },
  mounted() {
    this.restaurants = this.loadAll()
  },
  methods: {
    // 控制标签
    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1)
    },

    showInput(e) {
      this.dynamicTags.push(this.inputValue)
      // this.inputVisible = true
      // console.log(e)

      // this.$nextTick(_ => {
      //   this.$refs.saveTagInput.$refs.input.focus()
      // })
    },

    handleInputConfirm() {
      let inputValue = this.inputValue
      if (inputValue) {
        this.dynamicTags.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    // 带建议的输入框
    querySearch(queryString, cb) {
      var restaurants = this.restaurants

      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter(queryString) {
      return restaurant => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        )
      }
    },
    loadAll() {
      return [{ value: '标签1' }, { value: '标签2' }, { value: '标签3' }]
    },
    handleSelect(item) {
      this.dynamicTags.push(item.value)
      this.inputValue = ''
    }
  }
}
</script>

<style scoped="scoped">
/* 标签样式 */
.edit_layout .el-aside {
  height: 260px;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag,
.input-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  margin-bottom: 2px;
}
</style>
相关标签: vue vue