Making a Vue.js dropdown that is rendered dynamically compatible with the Select2 library

Having just started using Vue, I have a question regarding dynamically rendering a select dropdown and populating its options based on a computed property called filteredWidgets. This computed property depends on user selections made in other dropdowns. Here is the code snippet:

<div v-if="filteredWidgets.length > 0">
 <select id="widgetSelect" name="widgets">
      <option value="">Select up to two Widgets</option>
      <option v-for="widget in filteredWidgets" v-bind:value='widget.id'>
         @{{widget.name}}
      </option>
   </select>
</div>

According to Select2 documentation, this is how you can convert select/option elements into Select2 multiselect elements:

$(document).ready(function() {
    $('#widgetSelect').select2();
});

While this approach works for non-dynamically rendered pages, it doesn't suit Vue as the dropdown is rendered dynamically. The dropdown changes based on the selectedWidgets computed property. The challenge is to apply Select2 functionality to the widgetSelect dropdown when it appears or changes. Here is the method for the computed property filteredWidgets():

filteredWidgets() {
  var filteredWidgets = this.availableWidgets.filter(widget => {
     return widget.color == selectedColor && widget.size == selectedSize;
  });

  return filteredWidgets;
}

The default select dropdown renders correctly with the desired filtered widgets. However, the task now is to apply select2() to the widgetSelect dropdown immediately after it is rendered by Vue. I'm seeking guidance on the correct way to accomplish this.

Answer №1

Observe changes in filteredWidgets, and trigger .select2().

Observe: {
    async filteredWidgets() {
        await this.$nextTick() // wait for DOM to update
        $(this.$refs.widgetSelect).select2()
    }
}

To enable this, you must include a ref in the <select> element so that it can be accessed directly using this.$refs.widgetSelect, rather than using something like

this.$el.querySelector('#widgetSelect')
. The id attribute is no longer necessary unless used for another purpose.

<select ref="widgetSelect" name="widgets">

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

Tips for acquiring the initial fully visible item within a scrollable element with horizontal alignment through jQuery

I'm trying to use jQuery to find the first visible element inside a scrollable DIV, but I can't quite get it to work correctly. Can someone please help me identify what's causing the issue? $('div').on('scroll', functio ...

When the React application loads, loadingbar.js will be mounted initially. However, as the props or states are updated, the object

I recently made the switch from using progressbar.js to loadingBar.js in my React application for widget progress. Everything was working smoothly with progressbar.js, but once I switched to loadingBar.js, I encountered a strange issue. After the page load ...

Using JQuery to Send Form Data with an Ajax POST Request

On my web Node/Express app, I have implemented a basic messaging service and am currently attempting to submit the form using Ajax with the FormData object. While the form submission works perfectly without Ajax, all the req.body values are undefined when ...

How does Sizzle JS function?

While investigating the sizzle.js source code for a project, I stumbled upon an interesting discovery. Towards the end of the code, there is a line that reads: window.Sizzle = Sizzle; However, there doesn't seem to be any declaration of a variable n ...

Click on the event to save the document and print the HTML page

Is there a way to create an onclick event that saves the current HTML page as a document and then prints it? <html> <body> <div class="reportformat"> <div class="format1"> <table> <tr ...

Invoking AJAX function post readystatechange

Currently, I am in the process of making an Ajax call to a server and attempting to invoke another function once the response is ready (readystatechanged). As of now, there isn't any serverside code implemented. Surprisingly, Chrome and Firefox encoun ...

Ways to determine which value has been selected on the concealed tab

My knowledge in JavaScript is still developing and I have a question that I need help with. Essentially, I am trying to access a field within a tab that is not currently visible on the webpage. I am working on a questionnaire where users respond to questi ...

What is the most effective method for sharing a form across various components in Angular 5?

I have a primary form within a service named "MainService" (the actual form is much lengthier). Here is an overview- export class MainService { this.mainForm = this.formBuilder.group({ A: ['', Validators.required], B: & ...

What is the best way to manage URL data between a domain and hashtag using Vue Router?

I am currently developing a project using vue-cli, vue router, and node.js. The routing in Vue is set to hash mode so that users can easily navigate to specific pages by copying and pasting URLs or typing from memory without encountering any errors. Howeve ...

Tips for making a multiselect dropdown menu using bootstrap

I am working on a JavaScript application that parses data and displays it to users in a table generated by JavaScript. I am looking for a simple way to allow users to choose which fields to display in the table using a dropdown list or something similar. I ...

Preventing touch events on IOS while scrolling through my Cordova app

My app is created using Vuejs and built with Cordova. However, while testing my app on IOS, I noticed that when the user starts scrolling, accidentally touching a link doesn't stop the scroll but opens the link instead. How can I fix this issue? Ide ...

How to use AngularJS to collapse various panels with unique content

Hey everyone, I'm working on developing a collapsible panel using Angular. The panel should consist of a header and body to display the content. The desired behavior is that when a button is clicked, the content collapses down, and clicking the same b ...

Preventing the need to reset JavaScript text inputs

I'm encountering a strange issue in my code. I'm developing a graphing calculator that requires users to enter multiple expressions for evaluation. I have a text input and a button that adds a new input to the parent div whenever it is clicked: d ...

Basic Inquiry: Unhandled TypeError - Unable to access the property 'length' of an object that is not defined

Currently, I am utilizing a straightforward JSON Ajax request to fetch some JSON data. However, every time I attempt to use the JSON object, I encounter the following error: Uncaught TypeError: Cannot read property 'length' of undefined $(do ...

Javascript Code for toggling the visibility of a panel

I need help with a JavaScript code that can show or hide a panel depending on the data in a grid. If the grid has data, the panel should be displayed, but if the grid is empty, the panel should be hidden. I attempted to use the following code, but it did ...

Tips for transforming an Observable stream into an Observable Array

My goal is to fetch a list of dogs from a database and return it as an Observable<Dog[]>. However, whenever I attempt to convert the incoming stream to an array by using toArray() or any other method, no data is returned when calling the retrieveDo ...

Tips for maintaining DataTables filters after navigating Back/Forward or refreshing the page

We are currently utilizing DataTables for our table, and we are encountering difficulties in retaining the history of filters that were previously applied to the table. This would allow users to navigate back and forth and refresh through these filters. O ...

Identifying multiple instances of a specific string in a node.js file

Is it possible to detect multiple occurrences of the same string in a text file using Node.js? Here is my current code: const fs = require('fs'); var file_path = 'file.txt'; fs.readFile(file_path, "UTF-8", (error, data) => { if ...

"Assure that setTimeout will be executed within the then method in

Within an Immediately Invoked Function Expression (IFFE), I am returning a Promise. The first thing that is logged is first, followed by third, and then second. Despite having the setTimeout inside the then block, shouldn't everything within it be exe ...

REACT: Implement a feature to add a distinctive border around the currently selected image

When selecting a picture, I would like to have a border around it. Specifically, if out of 6 pictures I choose 3, I want highlighted borders around those selected images. How can this be achieved? EDIT: I am utilizing React to address this issue. ...