Looking to implement multiple select in Vue without using a library, I came across a useful jsFiddle code. Check it out here:
https://jsfiddle.net/02rafh8p/
To make this functionality available globally, I created a custom directive in another JavaScript file as shown below:
import Vue from 'vue';
export const Select = {
twoWay: true,
priority: 1000,
params: ['options'],
bind: function() {
let self = this;
$(this.el)
.select2({
data: this.params.options
})
.on('change', function() {
self.set($(self.el).val())
})
},
update: function(value) {
$(this.el).val(value).trigger('change')
},
unbind: function() {
$(this.el).off().select2('destroy')
}
};
Vue.directive('select', Select);
Next, I want to use this custom directive in my component:
<template>
<div id="el">
<p>Selected: {{selected}}</p>
<select v-select="selected" multiple :options="roles2" style="width: 400px; height: 1em;">
<option value="0">default</option></select>
</div>
</template>
import {Select} from '../select.js';
export default {
directives: {
Select
},
data() {
return {
form: new Form({
memberId: this.member.id,
firstname: this.member.user.firstname,
lastname: this.member.user.lastname,
email: this.member.user.email,
roles: Object.values(this.member.actual_roles),
rate: this.member.billing.rate,
currency: this.member.billing.currency_id,
type: this.member.billing.type
}),
fullname: this.member.user.full_name,
selected: [],
roles2: [
{id: 1, text: 'hello'},
{id: 2, text: 'what'}
]
}
},
}
Encountering the following error:
TypeError: Cannot read property 'el' of undefined
After modifying a piece of code in select.js like so:
let self = this;
$(this.el) => hange to : $('#el')
.select2({
data: this.params.options
}) ...
A new error arises:
TypeError: Cannot read property 'params' of undefined
This being my first attempt at creating a custom directive, I seek assistance in resolving these issues. Any help or advice on how to address these errors would be greatly appreciated.