【问题标题】:Using select2 with vuejs directive, data from html使用带有 vuejs 指令的 select2,来自 html 的数据
【发布时间】:2018-08-19 20:11:41
【问题描述】:

我尝试创建一个 vuejs2 指令,它将选择已经呈现的选择并将其包装到 select2 中。这部分正在工作,但没有选择选定的值:

Vue.directive('select', {
    inserted: function (el) {

        $(el).select2({
            matcher: modelMatcher,
            minimumResultsForSearch: 6,
            dropdownAutoWidth: true,
            width: 'auto'
        });

    }
});

任何想法如何做到这一点?这可能适用于 vuejs 1:

https://gist.github.com/themsaid/c0548e19f247b832ac4f

但不再工作了。

【问题讨论】:

    标签: javascript laravel vuejs2 jquery-select2


    【解决方案1】:

    问题是select2,更改后会抛出jQuery.Event Object,并且Vue 只对常规JavaScript 事件作出反应

    所以解决方案是,在初始化 select2 之后,监听它发出的 change jQuery.Event 并发出一个 change CustomEvent ,所以 Vue 将其拾取。

    当 Vue 选择 change CustomEvent 时,它会更新 v-model

    下面的演示。

    Vue.directive('select', {
      inserted: function(el) {
        var self = this;
        $(el).select2({
          //matcher: modelMatcher,
          //minimumResultsForSearch: 6,
          //dropdownAutoWidth: true,
          width: 'auto'
        }).on('change', function(e) {
          if (e.detail === "vue-directive") {
            return; // prevent stack overflow (i.e. listening to the event we threw ourselves)
          }
          // throw regular change (non jQuery) event, so vue reacts
          el.dispatchEvent(new CustomEvent("change", {
            detail: "vue-directive"
          }));
          return false;
        })
      }
    });
    new Vue({
      el: '#app',
      data: {
        states: ["AL", "AK", "AZ"],
        selectedState: "AK",
      }
    })
    <script src="https://code.jquery.com/jquery-3.3.1.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
    <script src="https://unpkg.com/vue"></script>
    
    <div id="app">
      <select v-model="selectedState" v-select>
        <option v-for="state in states" :value="state">{{ state }}</option>
      </select>
      <p>Selected State: {{ selectedState }}</p>
    </div>

    请注意,这只是一种方法,使用Vue's Custom Directives Hook Functions 有多种可能性。另请注意,我上面显示的示例比您提供的要点要简单得多,因为它不处理 unbind 钩子,例如。 OTOH,实现应该很简单。

    【讨论】:

    猜你喜欢
    • 2016-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多