"Selectize component in Vue automatically closes the dropdown menu once an item is

Having trouble developing a straightforward selectize vue component. The issue arises when I select an option while using v-model within the component; the dropdown closes automatically. However, when I remove the v-model, the dropdown remains open until the maximum number of items is reached.

HTML

<div id="app">
  <p>With Model: {{ selected }}</p>
  <selectize v-model="selected" :options="options" data-max-items="2"></selectize>

  <p>Without Model: {{ selected }}</p>
  <selectize :options="options" data-max-items="2"></selectize>
</div>

JS

Vue.component('selectize', {
  props: ['options', 'value'],

  template: '<select><slot></slot></select>',

  mounted() {
    $(this.$el).selectize({
      onInitialize: () => {
        this.$el.selectize.setValue(this.value, true)
      },

      onChange: (value) => {
        this.$emit('input', value)
      },

      ...this.mergedSettings,
    })
  },

  computed: {
    mergedSettings() {
      return $.extend({
        options: this.options,
      }, $(this.$el).data())
    },
  },

  watch: {
    value(value) {
      this.$el.selectize.setValue(value, true)
    },
  },
})

new Vue({
  el: "#app",
  data: {
    options: [
      { value: 1, text: "One"   },
      { value: 2, text: "Two"   },
      { value: 3, text: "Three" },
      { value: 4, text: "Four"  },
    ],

    selected: [],
  },
})

Check out this jsfiddle for a demonstration: https://jsfiddle.net/uk0g69s4/19/

Answer №1

Although not my proudest solution, it was the best option I could come up with.

Introducing a new attribute called SELF_CHANGED to differentiate between internal and external triggers...

Vue.component('selectize', {
  props: ['options', 'value'],
  data() {
    return {
      SELF_CHANGED: false
    }
  },
  template: `
    <select>
        <slot></slot>
    </select>
  `,
  mounted() {
    $(this.$el).selectize({
      onInitialize: () => {
        this.$el.selectize.setValue(this.value, true)
      },

      onChange: (value) => {
        this.SELF_CHANGED = true
        this.$emit('input', value)
      },

      ...this.mergedSettings,
    })
  },

  computed: {
    mergedSettings() {
      return $.extend({
        options: this.options,
      }, $(this.$el).data())
    },
  },

  watch: {
    value(value) {
      if (!this.SELF_CHANGED) {
        this.$el.selectize.setValue(value, true)
      }
      this.SELF_CHANGED = false
    },
  },
})

new Vue({
  el: "#app",
  data: {
    options: [{
        value: 1,
        text: "One"
      },
      {
        value: 2,
        text: "Two"
      },
      {
        value: 3,
        text: "Three"
      },
      {
        value: 4,
        text: "Four"
      },
    ],
    selected: [],
  },
})
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.8.5/css/selectize.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sifter/0.5.3/sifter.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/microplugin/0.0.3/microplugin.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/js/selectize.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>

<div id="app">
  <p>With Model: {{ selected }}</p>
  <selectize v-model="selected" :options="options" data-max-items="2"></selectize>
  <p>Without Model: {{ selected }}</p>
  <selectize :options="options" data-max-items="2"></selectize>
</div>

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

Establish an environment variable in webpack for apache2

Can you access a webpack environment variable outside of the node/js scope? I am working on a project using vueJS and TYPO3, where I need to load JS files from the node server during runtime. Otherwise, I want to load the pre-built JS files from the proje ...

Pusher message not being received

Hey there! I'm currently utilizing laravel broadcasting along with pusher to transmit data. I've managed to successfully send messages to pusher, however, I'm facing issues receiving them. Below are my code snippets; any assistance woul ...

Angular is patiently waiting for the Ajax service function to finish executing

Seeking help on retrieving the result of an $http request from my controller. Below is my service code : .service('postService', function($http, apiUrl) { return { post: function(uri, params) { $http.post(apiUrl + uri, ...

Best practice for organizing sort icons in a table with React and MaterialUI

I am currently implementing the following code in a tsx component. I am still learning about the various layout options available. You can view my code on this sandbox link. import React from "react"; import { ArrowDropUp, ArrowDropDown } from "@materia ...

Utilizing Ajax and jQuery to extract information from an XML file based on an identification number

Currently, I am looking for a way to showcase a specific product with its description from my XML file by using the product's ID. The structure of my XML file is shown below: https://i.sstatic.net/wFWgW.png Below is the JavaScript code I am using: ...

Issue with custom Javascript not executing in Internet Explorer versions 9 and 10

Initially, this script is found in the document's head section. <script> document.addEventListener("DOMContentLoaded", function () { var e, t = document.querySelectorAll("div.bounceInDown"); for (var n = 0, r = t.length; n & ...

Using jQuery to dynamically load content from a link using Ajax

How can I modify a link element with an href link to a page to use Ajax to load that content from the href URL without redirecting the user to that page? I want to inject the content into the current page. <a class="bind-jquery-event-here-class" href=" ...

What is the best way to combine text from various group radio buttons?

Here is the JavaScript code I have written: $(function(){ $('input[type="radio"]').click(function(){ var txt = $(this).parent().text(); var $radio = $(this); if ($radio.data('waschecked') == true) { ...

Getting headers from an HTTP response in VueJS is a common task that many developers encounter

I am utilizing axios to fetch data from the backend. After sending a request, I receive a response; however, I am struggling to read some of my headers. The headers that I need to access are 'content-type', 'content-length', 'x-wp- ...

Access the document on the desktop and open it in a new popup window

As a novice in html coding, I'm wondering if it's possible to write window size and other properties directly into the page. Let me explain. I'm currently working on a calculator and I want to run the HTML file on my desktop. Everything wor ...

VueJS - Validating Props with Objects

What is the best way to validate Object type props in VueJS to guarantee that certain fields are defined within the object? For instance, I need to make sure that the user prop includes 'name', 'birthDate', and other specific fields. ...

How to create a fresh factory instance in Angular Js

I have implemented a factory in my application to retrieve a list of folders and display it on the front end. Additionally, I have a form on the front end where users can add new folders to the existing list. After adding a folder, I need to refresh my fac ...

Tips for getting involved in the Mojito repository on Github for javascript development

Looking for guidance on studying, understanding, and debugging code? I have a good grasp of javascript but unsure where to begin. I am familiar with Github and Mojito, but struggling to contribute to the platform. Any tips on how to get started with Moji ...

Can HTML5 and JavaScript be used to clip a portion of a video and upload it directly to a server?

Currently, I am using Filereader to read a local video file (mp4) in order to display it in a video tag. However, I am looking to cut a specific part of the mp4 file (for example, from 5 to 10 seconds) and then upload it to a server. My current approach: ...

Modify Chartjs label color onClick while retaining hover functionality

Currently, I have implemented vue-chart-js along with the labels plugin for a donut chart. Everything is working well so far - when I click on a section of the donut chart, the background color changes as expected. However, I now want to also change the fo ...

Obtain the option tag's name

One of my challenges is working with a dynamically created dropdown in HTML and having a dictionary in the back-end to retrieve keys. As users keep adding options to the dropdown, I face the issue of not having a value attribute like this: <option valu ...

What is the best approach for handling an AJAX request on the server side?

Consider the function below: $.ajax({url:"http://127.0.0.1:8080", data: "123", success: function(response, textStatus, jqXHR) { alert(response); }, error: function(jqXHR, textStatus, errorThrown) { alert("An er ...

What is the process for retrieving wallet transactions using Alchemy websockets?

I am trying to retrieve all new transactions from a specific wallet using the code provided. However, I am encountering an issue when using the function tx["transaction"]["from"] to filter transactions based on the specified wallet. I am utilizing Alchemy ...

The property cannot be set because it is undefined in nodejs

var list = [ { title : '', author : '', content : '', } ] router.get('/japan',function(req,res){ var sql = 'select * from japan'; conn.query(sql,function(err,rows,fields){ for(var i = 0 ; ...

Extract website addresses from a text and store them in an array

I am currently attempting to extract URLs from a string and store them in an array. I have implemented a node module to assist with this task. const getUrls = require("get-urls") url = getUrls(message.content) However, the current implementation fails to ...