【发布时间】:2021-12-19 20:45:26
【问题描述】:
我有一个可以工作的 Vue 组件,它当前会为这样的选择呈现选项:
<select ref="subdomain_id" name="subdomain_id" id="newEvidenceSubdomain" class="form-control" :class="{ 'is-invalid': errors.subdomain_id }" v-model="subdomain">
<option value="none" selected disabled hidden></option>
<option v-for="choice in subdomains" :value="choice" >[[ choice.character_code ]]</option>
</select>
<div class="invalid-feedback" v-for="error in errors.subdomain_id">
[[ error ]]<br />
</div>
我正在尝试将其转换为 Select2 元素,以便用户更轻松地使用下拉菜单。
我在模板中有这个:
<div>
<p>Selected: {{ selected }}</p>
<select2 :subdomains="choices" v-model="subdomain">
<option disabled value="0">Select one</option>
</select2>
</div>
Vue 的其余部分如下所示:
<script type="text/x-template" id="select2-template">
<select>
<slot></slot>
</select>
</script>
<script>
Vue.component("select2", {
props: ["subdomains", "value"],
template: "#select2-template",
mounted: function() {
var vm = this;
$(this.$el)
// init select2
.select2({ data: this.subdomains })
.val(this.value)
.trigger("change")
// emit event on change.
.on("change", function() {
console.log('this a thing')
vm.$emit("input", this.value);
});
},
watch: {
value: function(value) {
// update value
console.log($(this.$el))
$(this.$el)
.val(value)
.trigger("change");
},
subdomains: function(subdomains) {
// update subdomains
$(this.$el)
.empty()
.select2({ data: subdomains });
}
},
destroyed: function() {
$(this.$el)
.off()
.select2("destroy");
}
});
</script>
'subdomains' 是我希望呈现的选项列表(您可以从工作的 HTML 版本中看到)。
当我尝试将其设为 Select2 对象时,我看到数据的“斑点”(就像它在那里一样,但为空白);但它只是一个带有不可见选项的选择。
我尝试了很多方法,但也许我误解了这应该如何渲染?
感谢所有帮助!
【问题讨论】:
-
能否提供vue和select2的版本?
-
Vue版本是2.6.14,Select2是4.1.0
标签: javascript html vue.js jquery-select2