Javascript 在Vue 2中呈现不带参数的组件指令

Javascript 在Vue 2中呈现不带参数的组件指令,javascript,vue.js,Javascript,Vue.js,我有一个保存学生名单数据的应用程序。组件应该接受该列表并呈现一个选择下拉列表(使用select2) 在fiddles控制台中,它显示jQuery未定义。我想现在所有的小提琴都包括jQuery 我真的不知道为什么这会打破所有。我的指令有问题吗?我知道Vue 2.0删除了参数,但这就足够了。任何对我的代码的眼睛将不胜感激 // Define component var studentsComponent = Vue.extend({ props: ['students'], data():

我有一个保存学生名单数据的应用程序。组件应该接受该列表并呈现一个选择下拉列表(使用select2)

在fiddles控制台中,它显示
jQuery未定义
。我想现在所有的小提琴都包括jQuery

我真的不知道为什么这会打破所有。我的指令有问题吗?我知道Vue 2.0删除了
参数
,但这就足够了。任何对我的代码的眼睛将不胜感激

// Define component
var studentsComponent = Vue.extend({
  props: ['students'],
  data(): {
    return {}
  },
  methods:{},
  directives: {
    select: {
        bind: function () {
        var self = this;
        var select = $('#select-student');

        select.select2();
        select.on('change', function () {
            console.log('hey on select works!');
         });
            },
      update: function (oldVal, newVal) {
        var select = $('#select-student');
        select.val(newVal).trigger('change');
      }
    },
  },
  template: `
    <div>
        <select
        ref=""
        id="select-student"
        v-select>
            <option value="0">Select Student</option>
            <option
            v-for="(student, index) in students" 
            :value="student.id">
            {{ student.name }}
            </option>
        </select>
    </div>
  `,
});

// Register component
Vue.component('students-component', studentsComponent);

// App
new Vue({
  el: '#app',
  data: {
    students: [
        { name: 'Jack', id: 0 },
      { name: 'Kate', id: 1 },
      { name: 'Sawyer', id: 2 },
      { name: 'John', id: 3 },
      { name: 'Desmond', id: 4 },
    ]
  },
});
//定义组件
var studentsComponent=Vue.extend({
道具:[学生],
数据():{
返回{}
},
方法:{},
指令:{
选择:{
绑定:函数(){
var self=这个;
var select=$(“#选择学生”);
select.select2();
选择.on('change',function(){
log('hey on select works!');
});
},
更新:函数(oldVal,newVal){
var select=$(“#选择学生”);
select.val(newVal.trigger('change');
}
},
},
模板:`
选择学生
{{student.name}
`,
});
//寄存器组件
Vue.component('students-component',studentsComponent');
//应用程序
新Vue({
el:“#应用程序”,
数据:{
学生:[
{name:'Jack',id:0},
{姓名:'Kate',id:1},
{name:'Sawyer',id:2},
{姓名:'John',id:3},
{name:'Desmond',id:4},
]
},
});

我做了一把小提琴作为参考。谢谢你帮了一个傻瓜

首先,正如我在评论中提到的,我建议您使用一个组件来实现这一点。但是,如果必须遵守指令,则不能在
bind
hook中初始化select2。您已经在DOM中定义了选项,因此需要等到插入组件后才能对其进行初始化

directives: {
    select: {
        inserted: function (el, binding, vnode) {
            var select = $(el);
            select.select2();
            select.on('change', function () {
                console.log('hey on select works!');
             });
        },
    },
},

是您的小提琴的更新。

文档地址直接选择2。是的,我看到了。但我觉得这在技术上也应该有效。。。有什么我遗漏的吗?喜欢指令不喜欢select2什么的@BertEvans:\您的代码中有一些错误<例如,code>data():{}应该是
data(){}
update
采用与bind相同的参数,而不是
oldVal、newVal