3👍
I don’t encourage mixing jQuery and Vue. For example in the snippet below which uses the jQuery select2 plugin you mentioned, once you do $('.select2').select2()
then the v-model="formData.allowance_id"
is useless because select2 does its own thing.
If you want to continue down this route and you’re submitting a form with ajax, you could get the value when you submit the form.
Concerning your Vue, data must be a function and mounted
isn’t part of data
.
EDIT:
After looking at the codepen for the Select2 – Wrapper component example that @Julia provided, there’s a change event you can subscribe to with select2, that you could use to update your model, something like this: .on("change", function() { self.onSelectChange(this.value); });
Vue.config.productionTip = false;
Vue.config.devtools = false;
new Vue({
el: '#app',
data: () => {
return {
allowances: [],
formData: {
allowance_id: null
}
};
},
mounted() {
this.getallowances();
let self = this;
$('.select2').select2().on("change", function() {
self.onSelectChange(this.value);
});
},
methods: {
onSelectChange(val) {
this.formData.allowance_id = val;
},
onSubmit() {
this.formData.allowance_id = $($(".select2")[0]).val();
},
getallowances() {
this.allowances = [{
id: 1,
name: "Test"
}];
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<select v-model="formData.allowance_id" id="allowance_id" name="allowance_id" class="form-control select2" required @input="alert('Test')">
<option :key="'allowance_id'" value="">choose allowance</option>
<option v-for="(allowance, index) in allowances" :key="allowance.id" :value="allowance.id">
@{{ allowance.name }}
</option>
</select>
<div>
<strong>Selected: </strong> {{formData.allowance_id}}
</div>
<div>
<button type="button" @click="onSubmit">Submit</button>
</div>
</div>
0👍
select2 hides the select and does its own thing, if you inspect the code, you’ll notice it. That’s why you cannot listen to the event on the select.
There’s an example of mixing a jQuery plugin and VueJS in the official doc Select2 – Wrapper component example