【问题标题】:Vue custom directiveVue 自定义指令
【发布时间】:2018-10-20 09:19:29
【问题描述】:

我需要在没有库的 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('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

这是我的第一个自定义指令,我不知道为什么它完全不起作用。有人可以帮我弄清楚吗?我什至不知道或者我的 jQuery 找到#el 是好的 :(

【问题讨论】:

    标签: javascript vue.js directive


    【解决方案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

    【讨论】:

      猜你喜欢
      • 2019-11-06
      • 2021-04-23
      • 1970-01-01
      • 2020-10-27
      • 2019-11-19
      • 1970-01-01
      • 2020-05-25
      • 2018-07-12
      • 1970-01-01
      相关资源
      最近更新 更多