Unable to add new tags in Vue multiselect component

Currently, I am utilizing a Vue Multiselect instance with two functions. One function interacts with the database to provide autocomplete functionality, which is working successfully. The second function allows for adding new tags that are not present in the database.

For instance, if 'Tag One' exists in the database, typing it and selecting it will save the tag to the list (multiselect with tagging enabled). However, when typing 'Tag Three' which is not in the database and selecting it, it simply vanishes without being added to the tags or triggering the axios function in my addTag method.

I am wondering what error I might be making in this context?

<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9bf7e1f194d4ccb5c8b0aba4a7cab890bcbdc09a84">[email protected]</a>"></script>
<script src="https://unpkg.com/@johmun/vue-tags-input/dist/vue-tags-input.js"></script>

<div id="tagApp">
  <multiselect
    label="tag_data"
    track-by="campaign_tag_id"
    v-model="value"
    :options="options"
    :multiple="true"
    :taggable="true"
    @tag="addTag"
    @search-change="val => read(val)"
    :preselect-first="false"
    :close-on-select="false" 
    :clear-on-select="true" 
    :preserve-search="true" 
    tag-placeholder="Add this as new tag" 
    placeholder="Search or add a tag"
  ></multiselect>
</div>

new Vue({
  components: {
    Multiselect: window.VueMultiselect.default
  },
  el: "#tagApp",
  data() {
    return{
        value: [],
        loading: false,
        options: []
    }

  },
  methods: {
    read: function(val){
      if (val) {
        this.loading = true;
        this.options = [];

        const self = this;
        console.log(val);

        axios.get('search',{params: {query: val}})
            .then(function (response) {
                self.options = response.data;
                console.log(response.data);
        });

      } else {
        this.options = [];
      }
    },
    addTag(newTag) {
      const tag = {
        tag_data: newTag,
      };
      const campaign_id = document.querySelector("input[name=campaign_id]").value;

      this.options.push(tag);
      this.value.push(tag);

      axios.post('tags/save',{
            tag_data: newTag,
      })
      .then(function (response){
            console.log(response);
      })
      .catch(function (error) {
            console.log(error);
      });
    }
  }
}) 

Answer №1

It seems like the issue might not lie with something you're doing wrong, but rather with the limitations of the component itself.

One potential workaround could be to ensure that the search term is always included in the options array if it's not already there. Incorporating the following code snippet within the axios callback may suffice:

self.options = response.data;
self.options.push(val)

This would allow you to rearrange the order or maintain the position of the added item, while also implementing measures to prevent duplicates and such.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using querySelector() to target specific divs by their classes while excluding any other classes

I am attempting to retrieve only the first divs while excluding the second ones: <div class="_5pcr userContentWrapper"> <div class="_5pcr userContentWrapper _4nef"> After researching, I discovered that the querySelector function should be abl ...

Animation fails to initiate when the object enters the viewport

I attempted to inject some enchantment into my project by implementing code from a tutorial found on this CodePen. However, I encountered an issue where the code only functions properly within that specific CodePen environment. Even after copying the same ...

Changing dates in JavaScript / TypeScript can result in inaccurate dates being displayed after adding days

Recently, I encountered an issue with a simple code snippet that seems to produce inconsistent results. Take a look at the function below: addDays(date: Date, days: number): Date { console.log('adding ' + days + ' days'); con ...

What is the most effective method for preserving RichText (WYSIWYG output)?

I am currently using a JavaScript-based rich text editor in my application. Could you suggest the most secure method to store the generated tags? My database is MySQL, and I have concerns about the safety of using mysql_real_escape_string($text);. ...

Vue.js is unable to dispatch an event to the $root element

I'm having trouble sending an event to the root component. I want to emit the event when the user presses enter, and have the root component receive it and execute a function that will add the message to an array. JavaScript: Vue.component('inp ...

Is it possible to click the back button on your browser and return to an ajax page while keeping it in the same appearance?

I've been researching different jquery history plugins, but I haven't come across any examples that fit my specific situation. This is leading me to believe that what I'm trying to accomplish may not be feasible. Our search page is highly c ...

Dynamically changing the date format within the item-text of v-autocomplete in Vuetify

My current v-autocomplete component is fetching an array of items from GrowthTasks.edges to display. <v-autocomplete label="Start Week" :items="GrowthTasks.edges" item-text="node.growthStartDate" item-value="node.grow ...

Nightwatch.js custom assertion for array comparison fails to function as expected

Utilizing the nightwatch-cucumber framework, which is built on top of Nightwatch.js, I am in the process of creating automated end-to-end tests. As a newcomer to 'JavaScript' and 'node.js', I encountered an error during the execution of ...

Nested loops combined with a timeout occasionally results in failure

I encountered a problem with the loops and timeouts in my script that I created for practice. If you want to take a look at the script, you can find it here: http://codepen.io/JulienBarreira/pen/EWNoxJ When running the script, I noticed that sometimes one ...

Is it possible to retrieve data from the server in Node.js/Vuetify based on a specific time frame?

I'm currently using a node.js server for my vuetify project. Within the server, I am parsing a csv file that contains scheduling and time information. Is there a method in my vuetify project to retrieve data from the csv file based on the current time ...

Require assistance in accessing the second tab on a webpage using JavaScript tabs

Currently, I have a web page with two tabs that are initially hidden until the corresponding tab button is clicked. The click event is managed by jQuery. For example, let's assume that tab 1 is the default one when the page loads. Now, I am looking fo ...

Guide to utilizing a JWT token within an httpOnly cookie for accessing a secured API endpoint

Utilizing next.js and next-auth for user login authentication with an API. Once the login is successful, a httpOnly cookie named __Secure-next-auth.session-token is stored in the browser. The following is a sample value (not actual data): eyJhbGciOiJIUzUxM ...

encase a function with javascript

let myString = "I am creating a program."; //function to calculate number of letters const letterCount = (str) => str.length; //function to calculate number of words const wordCount = (str) => str.split(" ").length; //function ...

Event not tracking properly due to missing label in GA event firing

Seeking assistance with a project I'm currently engaged in. I have created an HTML5 video containing a playlist and encountering difficulties setting up multiple labels in GA to track each individual video play. While I found code online, adapting it ...

Save this text in HTML format to the clipboard without including any styling

When using this code to copy a htmlLink to the clipboard: htmlLink = "<a href='#'>link</a>"; var copyDiv = document.createElement('div'); copyDiv.contentEditable = true; document.body.appendChild(copyDiv); ...

Detecting when an object exits the proximity of another object in ThreeJS

In my ThreeJS project, I have planes (Object3D) flying inside a sphere (Mesh). My goal is to detect when a plane collides with the border of the sphere so that I can remove it and respawn it in a different location within the sphere. I am wondering how I ...

Working with conditional statements in ReactJS and Javascript

As I navigate the circle object using arrow keys, I am facing a challenge in limiting its movement within the height and width of the svg area. Despite my efforts to use conditional statements, the ball tends to get trapped at the edges and fails to contin ...

Display numeric data when hovering over circles in the Google Maps API using Javascript

I recently implemented the Google Maps example code that displays a circle hovering over a city, with the size of the circle representing the population. I'm looking to enhance this feature by including numeric data display on mouseover as well. Any a ...

Display the modal in Angular 8 only after receiving the response from submitting the form

I am encountering an issue where a pop-up is being displayed immediately upon clicking the submit button in Angular 8, before receiving a response. I would like the modal to only appear after obtaining the response. Can someone assist me with achieving thi ...

Repetitive occurrences of events being emitted from a VueJS component

As my mouse cursor hovers over and exits my VueJS component, specific methods are triggered accordingly. The methods that execute when the cursor enters and leaves my component: // Included in the "methods" section of my Vue component file onMouseEnter( ...