Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Armani's avatar
Level 17

Vue js component with Choices js

I used Choices js to create a Vue js component like this:

<script>
	import Choices from 'choices.js';
	export default {
		props: ['options', 'name' , 'modelValue'],
		emits: ['update:modelValue'],
		mounted() {
	      new Choices(this.$refs.select, {allowHTML: true,removeItemButton: true}).setChoices(this.options, 'id', 'name', false).setChoiceByValue(this.modelValue);
	    }
	}
</script>
<template>
	<div class="mt-3">
        <select class="form-control mt-3" @change="$emit('update:modelValue', $event.target.value)" :value="modelValue" :name="name" ref="select">
        </select>
    </div>
</template>

everything works except when v-model value changes it won't update the select item (setChoiceByValue).

0 likes
1 reply
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

To update the select item when the v-model value changes, you can add a watcher to the component that listens for changes to the modelValue prop and updates the select item accordingly. Here's an example:

<script>
  import Choices from 'choices.js';

  export default {
    props: ['options', 'name', 'modelValue'],
    emits: ['update:modelValue'],
    mounted() {
      this.choices = new Choices(this.$refs.select, {
        allowHTML: true,
        removeItemButton: true
      }).setChoices(this.options, 'id', 'name', false).setChoiceByValue(this.modelValue);
    },
    watch: {
      modelValue(newValue) {
        this.choices.setChoiceByValue(newValue);
      }
    }
  }
</script>

In this example, we're creating a choices instance in the mounted hook and storing it as a component property. Then, we're adding a watch property to the component that listens for changes to the modelValue prop and updates the choices instance with the new value using the setChoiceByValue method.

Note that we're also using the this.choices property to access the choices instance in the watch handler. This is because the choices instance is not available in the component's scope outside of the mounted hook.

Please or to participate in this conversation.