在没有参数的情况下渲染Vue 2中的组件指令

问题描述:

我有一个保存学生列表数据的应用程序。该组件应该在该列表中并呈现选择下拉列表(使用select2)。在没有参数的情况下渲染Vue 2中的组件指令

在小提琴控制台中,它显示jQuery is not defined。我认为所有的小提琴现在都包含jQuery?

我真的不知道为什么这是一起打破所有。我的指令有问题吗?我知道Vue 2.0他们删除了params,但这应该就够了。任何眼睛在我的代码将不胜感激。

// 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 }, 
    ] 
    }, 
}); 

我做了一个小提琴https://jsfiddle.net/hts8nrjd/4/以供参考。感谢您帮助noob out!

+0

该文档直接地址select2。 https://vuejs.org/v2/examples/select2.html – Bert

+0

是的,我看到了。但我认为这在技术上应该工作以及...有什么我失踪?像指令不喜欢select2或什么? @BertEvans:\ – Modelesq

+0

您的代码中存在一些错误。例如'data():{}'应该是'data(){}'。 'update'采用与bind相同的参数,而不是'oldVal,newVal' https://vuejs.org/v2/guide/custom-directive.html#Directive-Hook-Arguments – Bert

首先,正如我在评论中提到的,我建议你用一个组件做这件事。但是,如果需要使用伪指令,则无法在bind钩子中初始化select2。你已经在DOM中定义了你的选项,所以你需要等到组件插入来初始化它。

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

Here是你的提琴的更新。

+0

'inserted'。非常感谢的朋友! – Modelesq