【问题标题】:Rendering a component directive in Vue 2 without params在没有参数的 Vue 2 中渲染组件指令
【发布时间】:2017-03-16 01:08:06
【问题描述】:

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

在小提琴控制台中,它显示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/ 供参考。感谢您帮助一个菜鸟!

【问题讨论】:

  • 文档直接地址 select2。 vuejs.org/v2/examples/select2.html
  • 是的,我看到了。但我认为这在技术上应该也可以工作......我有什么遗漏吗?喜欢指令不喜欢 select2 什么的? @BertEvans:\
  • 您的代码中有一些错误。例如,data():{} 应该是 data(){}update 采用与 bind 相同的参数,而不是 oldVal, newVal vuejs.org/v2/guide/…

标签: javascript vue.js


【解决方案1】:

首先,正如我在 cmets 中提到的,我建议您使用组件来执行此操作。但是,如果您不得不 坚持使用指令,则无法在 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 是你的小提琴的更新。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-19
    • 2018-12-17
    • 2017-03-21
    • 2018-05-04
    • 2017-11-07
    • 2023-03-24
    • 1970-01-01
    相关资源
    最近更新 更多