【发布时间】: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
}
})
<select v-select="select_options" v-model="user_id"></select>
问题是我需要在 mount() 调用时更新 select2 输入 我不知道我应该如何处理这个问题 如果有人知道我该怎么做,我将不胜感激。 如果您知道我从 API 提供信息并且选项的值将是每个选项的 id,我认为这将非常棒。
【问题讨论】:
标签: vue.js vuejs2 jquery-select2 vue-directives