Vue自定义指令

时间:2018-05-10 06:53:06

标签: javascript vue.js directive

我需要在Vue withut库中有多个select。我发现了一个很好的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('select',Select);

这是我想要拥有自定义指令的组件:

<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

这是我的第一个自定义指令,我不知道为什么它不起作用。有人可以帮我搞清楚吗?我甚至不知道或者我的jQ​​uery发现#el是好的:(

1 个答案:

答案 0 :(得分:1)

小提琴的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