fid*_*ido 3 vue.js vue-component vuejs2
很多天我一直在寻找这个错误的答案.我尝试了很多替代品但没有任何效果
我需要选择多个值.当我选择多个值时,我的代码会挂起,但是当我使用单个选择时,它可以正常使用self.$emit('input', this.value).我需要的是选择多个值.
Select2.vue
<template>
<select multiple class="input-sm" :name="name">
<slot></slot>
</select>
</template>
<style src="select2/dist/css/select2.min.css"></style>
<style src="select2-bootstrap-theme/dist/select2-bootstrap.min.css"></style>
<script>
import Select2 from 'select2';
export default{
twoWay: true,
priority: 1000,
props: ['options', 'value', 'name'],
data(){
return{
msg: 'hello'
}
},
mounted(){
var self = this;
$(this.$el)
.select2({theme: "bootstrap", data: this.options})
.val(this.value)
.trigger('change')
.on('change', function () {
//self.$emit('input', this.value) //single select worked good
self.$emit('input', $(this).val()) // multiple select
})
},
watch: {
value: function (value) {
$(this.$el).val(value).trigger('change');
},
options: function (options) {
$(this.$el).select2({ data: options })
}
},
destroyed: function () {
$(this.$el).off().select2('destroy')
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
new.vue
<p>Selected: {{ model.users_id }}</p>
<select2 :options="options" v-model="model.users_id" name="options[]" style="width: 1000px; height: 1em;" class="form-control">
<option value="0">default</option>
</select2>
export default {
data(){
return {
model: {
'users_id': [],
},
options: [],
components:{
'select2': Select2
},
Run Code Online (Sandbox Code Playgroud)
Ber*_*ert 12
看起来您使用了select2的包装器的Vue文档示例作为基础.我已经修改了包装处理多重选择这里.
我希望您遇到的主要问题是,如果您这样做:
self.$emit('input', $(this).val()) // multiple select
Run Code Online (Sandbox Code Playgroud)
你将最终进入无限循环,因为你正在发射一个新阵列,它将触发手表,
value: function (value) {
$(this.$el).val(value).trigger('change');
},
Run Code Online (Sandbox Code Playgroud)
触发更改,触发手表等.
要解决此问题,只需检查传入监视的值是否与select的值相同,如果是,则忽略它.这是我如何做到的.
value: function (value) {
// check to see if the arrays contain the same values
if ([...value].sort().join(",") !== [...$(this.$el).val()].sort().join(","))
$(this.$el).val(value).trigger('change');
},
Run Code Online (Sandbox Code Playgroud)
另请注意,我将其转换为自己的组件select2Multiple.您可能希望有一个组件处理多个选定值,另一个组件处理单个值.