首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Vue自定义指令

Vue自定义指令
EN

Stack Overflow用户
提问于 2018-05-10 14:53:06
回答 1查看 816关注 0票数 0

我需要在Vue没有库的情况下有多个选择。我找到了一个很好的jsFiddle代码。这里:

代码语言:javascript
复制
https://jsfiddle.net/02rafh8p/

我已经在另一个js中编写了这个指令,以使其全局如下所示:

代码语言:javascript
复制
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',选择);

下面是我想要在其中包含自定义指令的组件:

代码语言:javascript
复制
<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'}
            ]
        }
    },
}

第一个错误是:

代码语言:javascript
复制
TypeError: Cannot read property 'el' of undefined

当我在select.js中更改这段代码时:

代码语言:javascript
复制
 let self = this;
  $(this.el) => hange to : $('#el')
    .select2({
        data: this.params.options
    }) ...

然后我又犯了一个错误:

代码语言:javascript
复制
TypeError: Cannot read property 'params' of undefined

这是我的第一个自定义指令,我不知道为什么它不能完全工作。有人能帮我解决这个问题吗?我甚至不知道或者我找到#el的jQuery是好的:(

EN

回答 1

Stack Overflow用户

发布于 2018-05-10 15:51:20

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50267208

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档