You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Quasar框架q-input按词生成标签的问题求助

解决Quasar q-input输入单词生成标签的问题

问题根源

直接将数组类型的变量绑定到q-input的v-model时,组件会默认把输入的每一个字符作为数组的单独元素,导致每个字母都变成标签。要实现按单词生成标签,需要通过中间文本变量来处理输入内容,再分割成标签数组。

实现方案

模板部分

<q-input 
  outlined 
  v-model="inputText" 
  label="Add tags"
  @keyup.enter="addTag"
  @keyup.space="addTag"
>
  <template #prepend>
    <q-badge 
      v-for="(tag, index) in tags" 
      :key="index"
      class="mr-2"
    >
      {{ tag }}
      <q-icon name="close" class="ml-1" @click="removeTag(index)" />
    </q-badge>
  </template>
</q-input>

脚本部分(Vue3 Setup语法)

import { ref } from 'vue'

export default {
  setup() {
    const inputText = ref('')
    const tags = ref([])

    const addTag = () => {
      // 去除首尾空格,过滤空字符串和重复标签
      const newTag = inputText.value.trim()
      if (newTag && !tags.value.includes(newTag)) {
        tags.value.push(newTag)
        inputText.value = ''
      }
    }

    const removeTag = (index) => {
      tags.value.splice(index, 1)
    }

    return {
      inputText,
      tags,
      addTag,
      removeTag
    }
  }
}

脚本部分(Vue2选项式语法)

export default {
  data() {
    return {
      inputText: '',
      tags: []
    }
  },
  methods: {
    addTag() {
      const newTag = this.inputText.trim()
      if (newTag && !this.tags.includes(newTag)) {
        this.tags.push(newTag)
        this.inputText = ''
      }
    },
    removeTag(index) {
      this.tags.splice(index, 1)
    }
  }
}

关键说明

  • 用inputText(字符串类型)绑定q-input的v-model,避免组件直接操作数组
  • 监听回车和空格键触发addTag方法,将输入的单词添加到tags数组
  • 添加标签时自动过滤空字符串和重复标签,提升体验
  • 给标签增加关闭按钮,方便删除不需要的标签

内容的提问来源于stack exchange,提问作者Youssef Hlem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 12:13:09