Search code examples
vue.jsvue-multiselect

How to remove preselected tag in vue-multiselect


I need a dropdown that supports tagging and can be styled easily, so I decided to implement vue-multiselect. It works but the problem is that I have a predefined tag in my dropdown when the page loads and I don't what that, how can I remove it? Here is how it looks now:

pic1

and here is how I want it to look:

pic2

Here is my html code:

<div>
   <multiselect v-model="value" tag-placeholder="Add this as new tag" placeholder="Assesors" label="name" track-by="code" :options="options" :multiple="true" :taggable="true" @tag="addTag"></multiselect>
</div>

and here is my js:

data () {
    return {
     showAddUserDialog: false,

      value: [
        { name: 'Assesors', code: 'as' }
      ],
      options: [
        { name: 'Assesors', code: 'as' },
        { name: 'Finance', code: 'fi' },
        { name: 'Sales', code: 'sa' }
      ]
    }
  },
  methods: {
    addTag (newTag) {
      const tag = {
        name: newTag,
        code: newTag.substring(0, 2) + Math.floor((Math.random() * 10000000))
      }
      this.options.push(tag)
      this.value.push(tag)
    }
  }

Solution

  • Well, by the <multiselect> configuration you used and the expected behavior your showed...
    You have this https://i.sstatic.net/l0a7E.jpg to become this https://i.sstatic.net/mICHE.jpg

    I looks like you want to load your page only showing the placeholder, but if you'd like to only show your placeholder, you shouldn't have a value in the value variable, as you have:

    data () {
      return {
        showAddUserDialog: false,
        value: [
          { name: 'Assesors', code: 'as' } // <- remove this
        ],
        options: [
          { name: 'Assesors', code: 'as' },
          { name: 'Finance', code: 'fi' },
          { name: 'Sales', code: 'sa' }
        ]
      }
    }
    

    Because the behavior of the component is show your current tags, right?
    So if this tag is the placeholder, you can add it to the value when the user submits the form without choosing any other tag.

    But if you want to have it there as the value and trickery the component to only show it as a placeholder, I suggest you to deep dive in the docs about custom templating...

    Here talks about it https://vue-multiselect.js.org/#sub-custom-option-template
    And here talks about the tags slots https://vue-multiselect.js.org/#sub-slots

    Here is an example:
    Edit Multiselect Tag Example