I was working with select2 in vuejs , I found vuejs is not working with jquery select2 as vuejs is working with navite html.
I am using this code
Vue.directive('select', {
twoWay: true,
bind: function () {
$(this.el).select2()
.on("select2:select", function(e) {
this.set($(this.el).val());
}.bind(this));
},
update: function(nv, ov) {
$(this.el).trigger("change");
}
});
var app = new Vue({
el: '#app',
data: {
supplier_id: "niklesh"
}
})
$('#supplier_id').select2({});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.4/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.5/css/bootstrap.css">
<div id="app">
{{ supplier_id }}
<select id="supplier_id" class='form-control' v-model='supplier_id' v-select='supplier_id'>
<option value="atul">Atul</option>
<option value="niklesh">Niklesh</option>
<option value="sachin">Sachin</option>
</select>
</div>
Please share your reply to handle this problem.
4
Answers
By assigning select2 value to vuejs data I am able to fix this problem. I didn't use custom directive here.
Please comment if this is not good way or any better solution you suggest.
To get this to work with a directive, we need to understand how
v-model
works. From the docs:In the case of a select element,
v-model
will listen for thechange
event (notinput
). So, if the directive dispatches achange
event when the element changes, thenv-model
will work as expected.Here is an updated version of your code (works in Vue 2):
And here’s a version that works in Vue 3 (custom directives have different syntax, linked here):
Try add
v-on:change="onChange"
in your select controlHTML template
“onChange” is the name of your method
JavaScript