Using Vue Js directive to implement a Select2 component

I've been exploring the example of the Vue.js wrapper component and trying to customize it to use a v-select2 directive on a standard select box, rather than creating templates or components for each one.

You can view my implementation in this JS Bin.

The component structure is shown below (with the options set in the JS).

  <div id="app"></div>

  <script type="text/x-template" id="demo-template">
    <div>
      <p>Selected: {{ selected }}</p>
      <select2 :options="options" v-model="selected">
        <option disabled value="0">Select one</option>
      </select2>
    
      <p>Selected: {{ selected2 }}</p>
      <select2 :options="options" v-model="selected2">
        <option disabled value="0">Select one</option>
      </select2>

      <p>Selected: {{ selected3 }}</p>
      <select2 :options="options" v-model="selected3">
        <option disabled value="0">Select one</option>
      </select2>
    </div>
  </script>

  <script type="text/x-template" id="select2-template">
    <select>
      <slot></slot>
    </select>
  </script>

In the JavaScript section:

Vue.component('select2', {
  props: ['options', 'value'],
  template: '#select2-template',
  mounted: function () {
    var vm = this
    $(this.$el)
      .val(this.value)
      // initialize select2
      .select2({ data: this.options })
      // emit event on change.
      .on('change', function () {
        vm.$emit('input', this.value)
      })
  },
  watch: {
    value: function (value) {
      // update value
      $(this.$el).val(value)
    },
    options: function (options) {
      // update options
      $(this.$el).select2({ data: options })
    }
  },
  destroyed: function () {
    $(this.$el).off().select2('destroy')
  }
})

var vm = new Vue({
  el: '#app',
  template: '#demo-template',
  data: {
    selected: 0,
    selected2: 0,
    selected3: 0,
    options: [
      { id: 1, text: 'Hello' },
      { id: 2, text: 'World' }
    ]
  }
})

This is what I'm aiming for:

<div id="app">

    <p>Selected: {{ selected }}</p>
    <select name="selected1" id="selected1" class="select2" v-selectize v-model="selected">
        ... options here ...
    </select>

    <p>Selected: {{ selected2 }}</p>
    <select name="selected2" id="selected2" class="select2" v-selectize v-model="selected2">
        ... options here ...
    </select>

    <p>Selected: {{ selected3 }}</p>
    <select name="selected3" id="selected3" class="select2" v-selectize v-model="selected3">
        ... options here ...
    </select>

</div>

Answer №1

You have the flexibility to utilize your component in a manner that suits your needs, similar to how you would with a directive:

  <select2 name="selected1" id="selected1" v-model="selected">
    <option disabled value="0">Select one</option>
    <option value="1">Hello</option>
    <option value="2">World</option>
  </select2>

The name and id attributes will be passed down to the underlying select element.

In Vue 2, there is intentionally no straightforward method for achieving this using a directive. Unlike a component, a directive does not have direct communication with its parent component or Vue instance. A directive operates independently on a specific section of the DOM.

Ultimately, it doesn't offer any significant advantages to implement this using a directive rather than utilizing a component.

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

Transfer photos and videos to an external server using Javascript with Meteor framework

I currently have a meteor application hosted on Digital Ocean. I am considering setting up a dedicated server to store all images and videos separately from the site itself. Whenever a user uploads new media, it will be saved to this separate server. Does ...

Error encountered: When implementing mergeImages in express.js, a ReferenceError occurs stating that the window is not

I am encountering an issue while using mergeImages on my express.js server. The error message "ReferenceError: window is not defined" is displayed, but I am puzzled because I have not used the word 'window' in my code at all. Could you please rev ...

Tips for embedding Javascript code within the window.write() function

I have a JavaScript function that opens a new window to display an image specified in the data variable. I want the new window to close when the user clicks anywhere on it. I've tried inserting some JavaScript code within window.write() but it doesn&a ...

A guide to retrieving the timezone based on a specific address using the Google API

I need to utilize the Google API time zones, which requires geocoding the address to obtain the latitude and longitude for the time zone. How can I achieve this using a value from a textarea? Here are the 2 steps: Convert the textarea value into a geoc ...

Cufon failing to load following an ajax call

At first, cufon is used to replace the text on the main page. However, when another page file is loaded, cufon does not apply its replacement to the newly loaded content. Why is that? I tried adding cufon.refresh(); as the last function in the chain. I c ...

Why does the browser indicate that a GET request has been sent but the promise does not return anything?

Having trouble with a puzzling issue and unable to find any solutions online. I am attempting to make a basic HTTP get request to receive a JSON object from an API I created (using express+CORS). I have experimented with both Axios and VueResource, yet en ...

What could be causing my dangerouslySetInnerHTML to show altered content?

I am working on a project using React and have encountered an issue with the code: const externalMarkup = ` <a data-refpt='DN_0OKF_177480_ID0EMPAC' /> <ol> <li value='1'> <p> <strong&g ...

PhantomJS 2.0.0 not delaying page loading

In the script provided, there is an array of URLs called links. The function gatherLinks() is designed to collect additional URLs from the sitemap.xml file related to the ones in the links array. Once the number of URLs in the links array reaches a certain ...

The file field appears to be empty when sending a multipart/form-data request via AJAX

I'm encountering an issue when attempting to submit a multipart/form-data using AJAX. Here is the HTML code snippet: <form id='form_foto' method='post' enctype='multipart/form-data'> <input type='hidden ...

Ways to implement pointer event styling within a span element

Hi, I'm having trouble with styling and I can't seem to figure out how to resolve it. The style pointer-events: none doesn't seem to be working for me. Here is an example of my code: The style snippet: .noclick { cursor: default; ...

Contrasting createMuiTheme and getMuiTheme

When would you choose to use one over the other? What are the key differences in how they operate? ...

Tips for clearing a material-ui search input field with the help of a button

Currently, I am working on a tutorial that involves implementing react material-ui tables along with a search input textfield. I am attempting to enhance this by adding a button that not only resets the table report but also clears the search input textfie ...

Implement the anti-flickering script for Google Optimize in a NextJS/ReactJS environment

While working on a NextJS/ReactJS project, I am experimenting with setting up Google Optimize for some tests. One issue I have encountered is the flickering effect that occurs when Optimize changes visual elements during experiments. To address this probl ...

Troubleshooting: Node.js Express Server GET Handler Failing to Function

Recently, I've been attempting to build a GET request handler in Express.js. Here's the snippet of code I've put together: // include necessary files and packages const express = require('./data.json'); var app = express(); var m ...

Strategies for dividing a group of students into various teams with an equal balance of boys and girls

I am currently working on a programming project for school that involves assigning each student to a group in such a way that all groups have an equal number of boys and girls. In this project, there are two existing groups (A and B) with some students al ...

Simple method to retrieve the ID of an input field within a form using jQuery selectors

I have a form with each input field having a unique id, and I have attached a jQuery 'input' event to the form. I want to retrieve the id of the field on which the user changes some value using a jQuery function. There seems to be something missi ...

To give an element a class in Javascript (without using jQuery) if it is currently hidden

Apologies if this question is not perfect, as I am still learning. I have been struggling to figure out how to add a class to an ID when the class is hidden using pure JavaScript (without jQuery). Below are my attempts so far: function hidekeep() { ...

What is the best way to structure my protractor scenarios for effectively validating HTTP response errors?

My current setup involves using protractor to test the functionality of my Angular client, while the server is implemented using Python Google App Engine. In order to enhance my protractor test, I am looking to include an assertion on the http response ge ...

What is the best way to determine the size of the URLs for images stored in an array using JavaScript?

I am working on a project where I need to surround an image with a specific sized 'div' based on the image's dimensions. The images that will be used are stored in an array and I need to extract the height and width of each image before disp ...

What is the best way to display an error message when a necessary field is left empty?

I am currently utilizing a plugin to validate my form. My goal is to display an error message on the button when clicked, as all fields in my form are required and need validation. Despite attempting the code below, it hasn't been successful: <Fo ...