Utilize a fluid AJAX endpoint for the Vue Select2 encapsulated component

I have customized the Wrapper Component Example based on VueJS documentation by adding the AJAX data source feature. You can view my modified code here.

My goal is to dynamically set the ajax url property of my select2 component, like this:

<select2 :options="options" v-model="selected" url="dynamic-url-here">
  <option disabled value="0">Select one</option>
</select2>

Can you help me figure out how to achieve this?

Answer №1

  1. Include the property in the Component's props:

    Vue.component('select2', {
        props: ['options', 'value', 'url'],
    
  2. Transfer the AJAX options to a variable outside the select2 component or a data element within that component:

    Vue.component('select2', {
        props: ['options', 'value', 'url'],
        template: '#select2-template',
        data: function() {
          return {
              ajaxOptions: {
                  url: this.url,
                  dataType: 'json',
                  delay: 250,
                  tags: true,
                  data: function(params) {
                      return {
                          term: params.term, // search term
                          page: params.page
                      };
                  },
                  processResults: function(data, params) {
                      params.page = params.page || 1;
                      return {
                          results: data,
                          pagination: {
                              more: (params.page * 30) < data.total_count
                          }
                      };
                  },
                  cache: true
              }
          };
      },
    
  3. Utilize that variable when initializing the select2:

    mounted: function() {
        var vm = this
        $(this.$el)
           .select2({
               placeholder: "Click to see options",
               ajax: this.ajaxOptions
           })
    
  4. Create a watcher for the url property:

    watch: {
        url: function(value) {
            this.ajaxOptions.url = this.url;
            $(this.$el).select2({ ajax: this.ajaxOptions});
       }
    
  5. Assign the property as follows:

    <select2 :options="options" v-model="selected" :url="url">
    

    where url is defined in the data object of the application.

View a demonstration in this plunker example.

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

Placing a Div wrapper around the contents of two corresponding elements

I am currently attempting to wrap a div with the class name 'wrapped' around two other divs containing innerHTML of 'one' and 'two'. <div class='blk'>one</div> <div class='blk'>two</di ...

Issue with vue.js: inability to assign multiple classes using a variable component

I am trying to add multiple classes to a div element. One class is static, another one includes a variable, and the last one depends on an inner property. The code snippet below does not produce the desired output: <div v-for="card in cards" : ...

Fix Vue by deleting "public" from the file path

After removing the "public" from the URL path following this guide Laravel 5 – Remove Public from URL, I have encountered an issue with Vue scripts not working properly. Interestingly, if you add "public" back to the path, the script works fine (http:// ...

Conceal a row in a table using knockout's style binding functionality

Is it possible to bind the display style of a table row using knockout.js with a viewmodel property? I need to utilize this binding in order to toggle the visibility of the table row based on other properties within my viewmodel. Here is an example of HTM ...

Angular's UI Modal: utilizing inline template and controller functionality

I am looking to create a simple confirmation box using UI-modal, which I have used successfully for more complex modals in the past that load their template and controller from external files. However, this time I want something even simpler - just a basi ...

Updating text color with Ajax response value

I need assistance with updating the text color of a sensor value displayed using html/ajax. Currently, the sensor value is being displayed successfully, but I want the text color to change based on the value. Here's an example: if value < 50 then f ...

JQuery's addClass function is not functioning properly

Check out the code snippet below: function toggleAccessRequests() { var buttonValue = $("#showAccessRequests").val(); if (buttonValue == "Show") { $(".hideAccessRequest").removeClass("hideAccessRequest"); $("#showAccessRequests").v ...

Adjust date by one day using the Datetimepicker tool

I have been attempting to adjust the date of my input by one day either forward or backwards, but I seem to be stuck and not making any progress. Take a look at my code: function function backDay() { var date = $('input#datetimepicker').va ...

Eliminate the white background from the modal image

I'm facing an issue with an image displayed in a modal. The image has a white background that I want to remove so only the image itself is visible. https://i.stack.imgur.com/CG9Ne.png Here's the code snippet: <div id="myModal" class ...

Streamline your Salesforce application by automating drop down selections with XPath using Selenium WebDriver

https://i.stack.imgur.com/Eg9jc.pngAn application has been developed in Salesforce with a dropdown box containing items built using the <li> tag. However, I am unsure how to select a specific item from this design. <div id="Department__cformContr ...

Ensure the buttons within v-card-actions are responsive to different screen sizes

I am facing an issue with a v-card that contains three buttons (v-btn) within v-card-actions. Each button has long text on it, which is causing alignment problems on small screens. The buttons are not responsive and are still aligned horizontally from left ...

Retrieve the outcome of a mongoose query within a designated function

Seeking help with returning a result from my mongoose find operation. While similar questions have been asked before, this one is unique. Here's an example of my user: let UserSchema = new mongoose.Schema({ variable: {type: mongoose.Schema.Object ...

I have my server running on port 6666. I am able to receive a response from Postman, however, when I attempt to access localhost:6666 in my browser, it displays a message

[image description for first image][1] [image description for second image][2] [image description for third image][3] There are three images displayed, indicating that the server is operational and responding with "hello" in Postman, but there seems to ...

Error in syntax for jQuery's .find() method

Is there a mistake that's preventing the results from showing up? When I delete the code between the "FROM HERE" and "TO HERE" comments, everything seems to work fine (at least it shows up on screen). I have a feeling that the issue lies with the .fi ...

Obtain the current date from the data source to utilize in a Vuetify component

I am looking to incorporate a vuetify calendar that highlights today's date. How can I retrieve the current date and assign it as a variable in the data? Below is an example of calendar code from the Vuetify webpage for reference. This particular exa ...

Adding event listeners to elements created dynamically

I am facing an issue with some dynamically generated divs from a JavaScript plugin. The divs have a class .someclass which wraps existing divs. My goal is to add a class to the children of .someclass. I attempted to achieve this by using the following code ...

When using create-react-app, the value of 'process.env.NODE_ENV' can be accessed as either a string or a process object during runtime

Have you come across code that looks like this: if(process.env.NODE_ENV === 'development') { // Perform operations specific to DEVELOPMENT mode } Similarly, you might see process.env.NODE_ENV === 'production. When we run npm run ...

AngularJS ng-show will not function properly with newly added DOM elements

I am encountering an issue with ng-show directives on dynamically added DOM elements in AngularJS. The directives work fine when the page initially loads, but new elements that are added later do not have their expressions evaluated. Is there a way to prom ...

What could be the reason behind receiving an "undefined" message when attempting to access db.collection in the provided code snippet?

var express = require('express'); var GoogleUrl = require('google-url'); var favicon = require('serve-favicon'); var mongo = require('mongodb').MongoClient; var app = express(); var db; var googleUrl = new GoogleUrl( ...

Utilizing PHP Variables in Ajax Calls: Transferring Data between JS and PHP

I've been struggling to grasp how to pass information from PHP to JavaScript and vice versa. I've spent an entire night trying to figure this out and would really appreciate it if someone could help me understand how to send two variables to an a ...