Adding new options to a multi-select dropdown in Vue.js when fetching data using an

Greetings! I've been utilizing a modified wrapper to manage a multiple select for vue.js. My goal is to change the value of 'this' inside the vue component. Below is the snippet of my code.

<select2-multiple :options="car_options" v-model="input.classification">
       <option disabled value="0">Select one</option>
</select2-multiple>

Here's the corresponding script:

Vue.component('select2Multiple', {
  props: ['options', 'value'],
  template: '#select2-template',
  mounted: function () {
    var vm = this
    $(this.$el)
      // init select2
      .select2({ data: this.options })
      .val(this.value)
      .trigger('change')
      // emit event on change.
      .on('change', function () {
        vm.$emit('input', $(this).val())
      })
  },
  watch: {
    value: function (value) {
    alert(value);
       if ([...value].sort().join(",") !== [...$(this.$el).val()].sort().join(","))
        $(this.$el).val(value).trigger('change');
    },
    options: function (options) {
      // update options
      $(this.$el).select2({ data: options })
    }
  },
  destroyed: function () {
    $(this.$el).off().select2('destroy')
  }
});

var vm = new Vue({
    el: '#el',
    delimiters: ["[[", "]]"],
    data: {
        input: {
            classification: []
        },
    },
    created: function () {
        var vm = this;
        axios.get('http://jsonplaceholder.typicode.com/todos')
                                    .then(function (response) {
                                        $.each(response.data, function (i, item) {
                                            response.data[i].id = String(response.data[i].id);
                                            response.data[i].text = String(response.data[i].title);
                                            vm.car_options.push(response.data[i]);
                                        });
                                        vm.input.classification = ["2"];
                                    })
                                    .catch(function (error) {
                                       console.log(error);
                                    });   
    }
});

I am aiming to have vm.input.classification = ["2"] pre-selected by default. Unfortunately, it seems like it's not working as expected and no error message is being displayed. While I'm not an expert in vue components, I believe that the issue lies within the vue component structure.

For reference, here's a link to the js fiddle example: here.

Answer №1

At last, the solution has been uncovered. The key lies in swapping the positions of options and the value of the component watch.

watch: {
    options: function (options) {
      // updating options
      $(this.$el).select2({ data: options })
    },
    value: function (value) {
       if ([...value].sort().join(",") !== [...$(this.$el).val()].sort().join(","))
        $(this.$el).val(value).trigger('change');
    }
  },

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

The date conversion within AngularJS's interpolation is resulting in an incorrect timestamp

Given a timestamp of 1519347000, I am trying to convert it into a date format using interpolation like so: {{$ctrl.myTimestamp | date:'MMM d y, hh:mm'}} The resulting value is Jan 18 1970, 04:02, which is incorrect. The correct date should be F ...

Using an AngularJS directive to modify CSS styles

I'm attempting to modify DOM CSS styles using Angular. If the textbox value is set as the height, I have assigned ng-model to the textbox and then ng-style="{height:heightdef}" How can I achieve this using a directive? Fiddle :: http://jsfiddle.n ...

Receiving the result as well as encountering undefined initially during AJAX request

I have a dropdown menu, and when a user selects an option, an AJAX call is made to retrieve and display data based on the selected value. If the dropdown value is 2, it triggers the AJAX request. However, I am encountering two issues: https://i.sstatic.n ...

Tips for displaying the HTML content within the autocomplete box

My situation involves a text input and an HTML form where users can submit their name to retrieve information. I am using AJAX to display the usernames dynamically. <div class="hidesearch" id="search" style="width:"400px;"> <inp ...

The JavaScript function is not returning the correct string when implemented in an HTML

I have written a function in a JavaScript file to return a string, and I am calling this function within a script tag inside an HTML file. function getExp() { var exp = "]]><!\\[CDATA\\["; return exp; } However, when I c ...

The Symfony API failed to generate a response

There seems to be a problem when trying to link the Symfony API with a React application. The API is not providing any response, even though it works fine when accessed directly through the link. ApiDirectURL Fetching this data from the React app is yiel ...

Is there a way to execute this process twice without duplicating the code and manually adjusting the variables?

I'm looking to modify this code so that it can be used for multiple calendars simultaneously. For example, I want something similar to the following: Here is what I currently have: This is my JavaScript code: var Calendar = { start: function () ...

The transformer construction failed due to an error: Module 'vue-native-scripts' not found

Encountering an issue while attempting to set up Vue-Native with Expo on iPhone, the error message in the expo app reads: Metro has encountered an error: Cannot read property 'transformFile' of undefined: Web/Rayrok/apps/the-bible/node_modules/me ...

React Native displaying identical path

Is there a way to dynamically change routes in React Native when a button is pressed? Inside my SplashContainer component, I have the following method: handleToSignUp = () => { console.log("Running handleToSignUp") this.props.navigator.push({ ...

Maintain MUI Autocomplete in the open state even after making a selection from the

Whenever I select certain options on my Autocomplete component, I want to keep the component open. However, each time I click on onChange, the Autocomplete closes automatically and I can't seem to find a way to prevent this. Is there a workaround? In ...

express-validator never accepts valid input

Currently, I am working on a project using the most recent version of nodejs and express. The basic site setup is complete, and now I am focusing on implementing user authentication based on what I've learned from this course. However, no matter what ...

How can I show the remaining paragraph text upon clicking a button in a responsive manner using CSS and JavaScript?

I want to add a nice animation effect to the height of my text when a button is clicked. I've managed to achieve this by setting a height: 30px with overflow: hidden initially, and then toggling a class with height: 300px. However, I'm facing an ...

The creation of transparent objects in THREE.js allows for a dynamic display of overlaid objects in the

Greetings, I am interested in creating a three.js room where the walls behind which objects are located (from the perspective of the camera) will become transparent with 50% opacity as I rotate the room. Allow me to elaborate: Visualize a scenario whe ...

"Encountering an error with ExpressJS where it cannot GET a file, preventing access to other folders' content

My goal is to set up a simple server using expressJS to retrieve data for my Angular application. However, I've encountered an error that says 'Cannot GET/'. This is the code snippet of the webserver I attempted to create: var express = re ...

Is there a way for me to retrieve the element that is linked to the ng-disabled attribute?

Is there a way to access the element with the ng-disabled attribute inside the function without passing it as a parameter? Here is the HTML element: <input class="needsDisabling" ng-disabled="isFieldDisabled()" type="text"> The isFieldDisabled fu ...

setting a callback function as a variable

I have encountered an issue where I am passing a callback function but unable to call it when the onreadystatechange changes its value, specifically request.onreadystatechange = func. Even though I receive a response from the server when making the ajax ...

Is it possible to blur all elements of a form except for the submit button?

Can someone help me with a form issue I am facing? <form> <input type="text>' <input type="submit">' </form>'' After submitting the form, I would like to blur the entire form: $(this).closest('form') ...

Getting the id of a row from a v-data-table in VueJs

I am currently facing an issue with retrieving the id of a specific field from each row. I require this id as a parameter for a function that will be utilized in an action button to delete the row. Here is how my table template appears: <template ...

A guide on resetting a Nodemon server using code

At the beginning of server start, I have an array of JSON objects that are updated. But if I make changes to the JSON data using NodeJS FS instead of manually editing it, Nodemon does not restart. Is there a way to programmatically restart nodemon? ...

Determine the moment when jQuery's load() function completes the loading of several images

My script utilizes jQuery's getScript() function to dynamically retrieve blog posts from Tumblr accounts. The response from the script is a JSON structure called tumblr_api_read, which includes image URLs among other things. function read(blogName) ...