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

Node.js poses a challenge when it comes to decoding incoming request data

I am attempting to create a sample login page using the combination of node, express, and angularjs. Displayed below is my login view: <div class="login-page"> <div class="login-page-content"> <div style="margin-top:30px;padding:10px;w ...

Tips for setting up bidirectional communication with props in a Vue.js component

Within my Vue.js component, I am utilizing the "name" props obtained from the parent component. My goal is to establish a two-way communication between the parent and child components using this props. The parent component code looks like this: <script ...

What is the best way to gather user input and incorporate it into a selected template, ensuring it is verified before sending?

I'm in the process of developing a project that involves gathering user input through a collector and displaying it on my template for verification before sending it out. The format I'm aiming for can be seen here: This is the template format I ...

Creating a new buffer by extracting a segment of another buffer in Node.js

Currently, I am executing an AWS call in Node.js that returns a buffer. var aws = new AWS.S3(); var params = { Bucket: s3config.bucket, Key: s3config.tile_directory + filepath //, // Range: 'bytes=0-' + (this.HEADER_SIZE - 1) }; ...

Have you ever wondered why a listener on the 'data' event interprets two separate requests as one, unless a timeout is added?

It seems that there is a tricky issue with node where it combines 2 different requests into one unless a timeout is added. In the code snippet below, if we write 'one' and 'two' to the server and push the result to an array, node interp ...

Using jQuery and Laravel framework to handle a POST request

Could someone assist me with troubleshooting a jQuery post request issue? I suspect there may be an error with the routes or controller. Here is my JavaScript code for the post request: $.post('http://localhost:8000/ajax', { ...

Display the current language in the Vue language dropdown

My component is called DropdownLanguage.vue Goal: I need to show the current active language by default in the :text="selectedOptionDropdown" attribute. For example, it should display "English" which corresponds to languages.name. I'm struggling with ...

The content of the text does not align. Alert in React 16

Currently, I am working on developing a ReactJs application with server-side rendering. Here are my entry points for both the client and server: client.jsx const store = createStore(window.__INITIAL_STATE__); hydrate( <Provider store={store}> ...

Visualize data retrieved from a third-party website through scraping in a chart

After attempting to extract data from a website's data.asp file (formatted in json) and display it as a chart on my site using Google Chart API or FusionCharts, I'm facing issues. Although I can retrieve the json data, it doesn't render as a ...

Ensure that Angular resolver holds off until all images are loaded

Is there a way to make the resolver wait for images from the API before displaying the page in Angular? Currently, it displays the page first and then attempts to retrieve the post images. @Injectable() export class DataResolverService implements Resolv ...

Building a custom event bus in Vue 3: A step-by-step guide

There's a need for a centralized event bus to enable communication between components on a single page. In Vue 2, I achieved this by creating a global context object and assigning fields to it during page creation. This context was then utilized acros ...

Session Redirect Error in Express.js

Encountering an error consistently when running my code with the pseudocode provided below (Just to clarify, my code is built on the react-redux-universal-hot-example) Error: Can't set headers after they are sent. [2] at ServerResponse.OutgoingMe ...

Guide to transferring a calculated outcome to a parameter in vue2.js

Is it possible to pass a computed result as a parameter in Vue.js? <el-input v-model="ruleForm.volexp"/>{{ calVol }} = {{ ruleForm.vol }} data() { return { ruleForm: { volexp: '', vol: 0 } } }, computed: { calVol: function() { ...

Encountered an exception while trying to retrieve data with a successful status code of 200

Why is a very simple get() function entering the catch block even when the status code is 200? const { promisify } = require('util'); const { get, post, patch, del } = require('https'); //const [ getPm, postPm, patchPm, deletePm ] = [ ...

Struggling to make PayPal Cordova Plugin function properly in both production and sandbox modes

While using the cordova paypal plugin and switching to sandbox mode, I encountered an error. The plugin can be found at https://github.com/paypal/PayPal-Cordova-Plugin https://i.stack.imgur.com/lD2EH.png Running the plugin in PayPalEnvironmentNoNetwork m ...

Anime.js: Grid layout causing issues with displaying simple text animations

I'm attempting to create a text animation within a grid layout using the anime.js library, but unfortunately, the animation isn't displaying. The project consists of just one HTML file. The JavaScript code: <script> import anime from &ap ...

What is the Vue.js alternative to setTimeout?

I'm currently in the process of developing a shopping cart feature using Laravel and Vue. In my system, when an item is added to the shopping basket, I want to display a confirmation message by toggling a Vue variable that is being monitored through a ...

Modifying specific attributes of an object within the $scope: A step-by-step guide

When working with Angular, if you have code in the view that looks like this: <span ng-model="foo.bar1"></span> <span ng-model="foo.bar2"></span> <span ng-model="foo.bar3"></span> Due to how Angular maps objects, you c ...

Employ a class function within router.get

I'm a beginner with node.js and I'm running into an issue when trying to use a class method in the router.get callback function. Can someone assist me with this problem? Route.get() is expecting a callback function but received a [object object] ...

Removing data from firestore/storage does not follow the expected pathway

I have created an image gallery for users using Firebase Storage and React, allowing them to upload and delete images. However, I am facing an issue where the deletion process is taking longer than expected. Expected flow: User clicks on the trashcan ico ...