在作select2插件的時候遇到一些坑,最終解決以下:vue
Vue.directive('select2', { inserted: function (el, binding, vnode) { var options = binding.value || {}; var defaultOpt = { placeholder: "--請選擇--", allowClear: true }; options = _.assign(defaultOpt, options); $(el).select2(options).on("select2:select", (e) => { // v-model looks for // - an event named "change" // - a value with property path "$event.target.value" el.dispatchEvent(new Event('change', { target: e.target })); //雙向綁定不生效 //綁定選中選項的事件 options && options.onSelect && options.onSelect(e); }); //allowClear:清除選中 $(el).select2(options).on("select2:unselecting", (e) => { //清空這個值,這個值即vuejs model綁定的值 e.target.value = ""; el.dispatchEvent(new Event('change', { target: e.target })); //雙向綁定不生效 }); //綁定select2 dom渲染完畢時觸發的事件 options && options.onInit && options.onInit(); }, update: function (el, binding, vnode) { $(el).trigger("change"); } });