【问题标题】:Append an option and make it as a selected value in the select2 directive in vue 2在 vue 2 的 select2 指令中附加一个选项并使其成为选定值
【发布时间】:2021-11-18 19:41:38
【问题描述】:

我在 vue 2 中创建了一个 select2 指令,如下所示:

// Select2 directive file

import Vue from "vue";

function updateFunction (el, binding) {
    setTimeout(() => {
        Vue.nextTick(function () {
            let options = binding.value || {};
            $(el).select2(Object.assign({}, {
            }, options))
            .on("select2:select select2:unselect", (e) => {
                el.dispatchEvent(new Event('change', { target: e.target }));
            })
            .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;
              });
        });
    }, 500);
}

// Initialize the directive.
export const select = {
    inserted: updateFunction,
    componentUpdated: updateFunction,
    params: ["placeholder"]
};

Vue.directive("select2", select);

我在 vue 文件中使用 select2,如下所示:

import { select } from "./directives/select2";

new Vue({
  data() {
    return {
      user_id: "",
      select_options: {
        ajax: {
            url: "/myAPI",
            headers: {
              "Content-Type": "application/json",
              Authorization:
                  "Bearer " + localStorage.getItem("api_token")
            },
            dataType: "json",
            processResults: function(data) {
              // Tranforms the top-level key of the response object from 'items' to 'results'
              var json = [];
              for (var i = 0; i < data.data.length; i++) {
                  var config = {
                      id: "",
                      text: ""
                  };
                  config.id = data.data[i].id;
                  config.text = data.data[i].name;
                  json.push(config);
              }
              return {
                  results: json
              };
          }
        }
      }
    }
  },
  directives: {
      select
  }
})
&lt;select v-select="select_options" v-model="user_id"&gt;&lt;/select&gt;

问题是我需要在 mount() 调用时更新 select2 输入 我不知道我应该如何处理这个问题 如果有人知道我该怎么做,我将不胜感激。 如果您知道我从 API 提供信息并且选项的值将是每个选项的 id,我认为这将非常棒。

【问题讨论】:

    标签: vue.js vuejs2 jquery-select2 vue-directives


    【解决方案1】:

    我是这样解决问题的:

    import { select } from "./directives/select2";
    
    new Vue({
      data() {
        return {
          user_id: "",
          select_options: {
            name: "this is a test",
            id: "1",
            ajax: {
                url: "/myAPI",
                headers: {
                  "Content-Type": "application/json",
                  Authorization:
                      "Bearer " + localStorage.getItem("api_token")
                },
                dataType: "json",
                processResults: function(data) {
                  // Tranforms the top-level key of the response object from 'items' to 'results'
                  var json = [];
                  for (var i = 0; i < data.data.length; i++) {
                      var config = {
                          id: "",
                          text: ""
                      };
                      config.id = data.data[i].id;
                      config.text = data.data[i].name;
                      json.push(config);
                  }
                  return {
                      results: json
                  };
              }
            }
          }
        }
      },
      directives: {
          select
      }
    })

    我把指令改成了这样

    function updateFunction (el, binding) {
        setTimeout(() => {
            Vue.nextTick(function () {
                if (binding.value.name && binding.value.id) {
                    var newOption = new Option(
                        binding.value.name,
                        binding.value.id,
                        false,
                        false
                    );
                    $(el)
                        .append(newOption)
                        .trigger("change");
                }
                let options = binding.value || {};
                $(el).select2(Object.assign({}, {
                }, options))
                .on("select2:select select2:unselect", (e) => {
                    el.dispatchEvent(new Event('change', { target: e.target }));
                })
                .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;
                  });
            });
        }, 500);
    }

    它将调查绑定值中是否存在名称和id,并将其设置为启动选项。

    【讨论】:

      猜你喜欢
      • 2017-11-01
      • 1970-01-01
      • 2020-04-25
      • 2014-07-12
      • 2022-11-17
      • 2017-06-25
      • 2011-10-29
      • 2020-03-31
      • 1970-01-01
      相关资源
      最近更新 更多