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

In need of styling text using CSS?

Despite setting the CSS to .text { word-wrap : break-word; max-width: 100px}, the text is not wrapping as expected. It is still displaying in a single line. I am anticipating that the large text should wrap onto the next lines. ...

JavaScript in fullscreen mode for Internet Explorer

I'm trying to make sure that this code snippet... $('#gatewayDimmer').width($('html').width()); $('#gatewayDimmer').height($('html').height()); $('#gatewayDimmer').css('display','block& ...

I am experiencing issues with the functionality of the navigation drawer on my page (using Vuetify)

One challenge I'm facing is with a vuetify navigation drawer within the navbar of my vuejs app. While it opens and closes properly, none of the items inside are clickable as they should be acting as links to other pages. Currently, only the logout but ...

To restore the position of the chosen object in Three.js after clicking reset

I am facing an issue with resetting the position of my latest Object in three.js. Initially, my code consists of the following: function onDocumentMouseDown( event ) { event.preventDefault(); var vector = new THREE.Vector3( mouse ...

What is the process for creating a selector that links to an element that has been dynamically generated?

Can anyone help me figure out how to create a selector that links to a dynamically created element without using an event on the dynamic element? By dynamically created element, I mean an element that is not present in the HTML at the beginning. I know t ...

Is it possible to navigate between jQuery EditInPlace fields using the Tab key?

Seeking advice on implementing tab functionality for a page with multiple jquery EditInPlace fields. The goal is to allow users to navigate between fields by pressing the tab key. Currently using the 'jquery-in-place-editor' plugin available at: ...

The loop is being controlled but the data is not being added and shown in the HTML div

I am struggling to display JSON data in an HTML div using a for loop. While my control is entering the loop, the data is not being appended and displayed in the HTML div. Here is the JSON data: [{"id":"15","FirstName":"ranjan","MiddleName":"","LastName": ...

Display a modal dialogue with an image on the initial page load for each user

Working on a project with Angular 11, Angular material, and Bootstrap, I encountered an issue. I want to display a popup ad the first time a user visits the home page. The modal dialog is created using Angular material, and I have it in the ads component, ...

Is there a way to assign retrieved data to the $scope.variable?

I'm relatively new to both JavaScript and Angular. I have a piece of code that fetches data from an API and successfully prints it to the console, but I'm facing issues when trying to assign this data to $scope.saveData. It seems to only work wit ...

Discovering the version of the Javascript library utilized on a website - a step-by-step guide

My quest is to uncover the versions of JavaScript libraries being utilized by popular websites. By using phantomjs.exe, I successfully identified the version information for jquery. However, I am currently at a loss on how to expand this capability to inc ...

Error: The code has a syntax issue due to an unexpected "function" token while using

Recently, I decided to try out Node version 6.2.1 with some of my code. My goal was to migrate the hyper-callback oriented codes to a cleaner and potentially more efficient approach. Surprisingly, when I attempted to run the node code in the terminal, an ...

Using a JavaScript loop to modify the color of the final character in a word

I am curious to find out how I can dynamically change the color of the last character of each word within a <p> tag using a Javascript loop. For example, I would like to alter the color of the "n" in "John", the "s" in "Jacques", the "r" in "Peter" ...

The specified instant cannot be located in 'moment' while attempting to import {Moment} from 'moment' module

Struggling in a reactJS project with typescript to bring in moment alongside the type Moment Attempted using import moment, { Moment } from 'moment' This approach triggers ESLint warnings: ESLint: Moment not found in 'moment'(import/n ...

Unable to initiate the server generated by the express.js generator

Currently, I am trying to set up an Express.js server using their generator. Following the documentation, I was able to successfully create the basic structure. However, when attempting to run the prescribed command (SET DEBUG=transcriptverificationserver: ...

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 ...

Text input setting for jQuery UI Slider

Currently, I am utilizing jQuery UI sliders to input values in text boxes. However, I would like this functionality to be bidirectional; meaning if a value is entered into the text box, I want the slider to move to the corresponding position. I am unsure ...

The results of the jQuery selector appear differently in the browser console compared to PhantomJS

What could be causing the discrepancy in results when using the same jQuery selector? Visit this website for reference: See below code involving node.js and phantomjs-node(bridge): phantom.create(function(ph){ ph.createPage(function(page){ p ...

Is there no body sent in the $.ajax post request?

My server is returning an error when I try to make a simple post request. It's saying that the post request has no body and all the keys have an "undefined" value. Here is the code for my post request: let alert_title = 'Alert'; let alert ...

Background image not displaying in new tab after Chrome extension installation

I have been developing a Chrome extension that alters the background image of a new tab. However, I have encountered an issue where the background image doesn't change the first time the extension is loaded. This problem has also occurred very occasi ...

Can you explain how the functionality of setState operates within React in this specific situation?

I've been working on updating the state of an object in my array. I managed to get it done, but I'm a bit confused about how it works. toggleVisited = countryCode => { var countries = [ ...this.state.countries ]; var countryToChange = c ...