Vue пользовательская директива - PullRequest
0 голосов
/ 10 мая 2018

Мне нужно иметь множественный выбор в библиотеке Vue без библиотеки. Я нашел хороший код jsFiddle. Здесь:

https://jsfiddle.net/02rafh8p/

Я должен написать эту директиву в другом js, чтобы она была глобальной:

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 («выберите», выберите);

А вот мой компонент, где я хочу иметь свою пользовательскую директиву:

<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'}
            ]
        }
    },
}

И первая ошибка:

TypeError: Cannot read property 'el' of undefined

Когда я изменяю в select.js этот кусок:

 let self = this;
  $(this.el) => hange to : $('#el')
    .select2({
        data: this.params.options
    }) ...

тогда у меня есть другая ошибка:

TypeError: Cannot read property 'params' of undefined

Это моя первая пользовательская директива, и я не знаю, почему она не работает полностью. Может кто-нибудь помочь мне разобраться? Я даже не знаю, или мой jQuery, чтобы найти #el, goood: (

1 Ответ

0 голосов
/ 10 мая 2018

vue версия вашей скрипки - 1.0.16. https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.16/vue.js

Я думаю, что вы используете последнюю версию VUE. Так что вам нужно будет следовать инструкции https://vuejs.org/v2/guide/custom-directive.html.

...