我正在尝试从select2中选择多个项目,但我不知道问题出在哪里。我的父组件没有获得选定的值,我需要它来传递所有选定的值。我正在使用vue.js 2.1.0
sub.vue
<select2 :options="options" v-model="selected" name="options[]">
<option disabled value="0">Select</option>
</select2>
data(){
return{
selected: [],
options: [],
}
},
mounted(){
this.fetchOptions(this.$route.params.id);
this.fetchSelected(this.$route.params.id);
},
created(){
this.fetchOptions(this.$route.params.id);
this.fetchSelected(this.$route.params.id);
},
methods: {
fetchOptions(id) {
var that = this;
$.get('/subject/' +id+ '/edit', function(data, status){
that.options = _.map(data.options, function (data) {
var pick = _.pick(data, 'name','id');
var opject = {id:pick.id, text:pick.name};
return opject
})
})
},
fetchSelected(id) {
var that = this;
$.get('/subject/' +id+ '/edit', function(data, status){
that.selected = _.map(data.selected, function (data) {
var pick = _.pick(data, 'name','id');
var opject = {id:pick.id, text:pick.name};
return opject
})
})
},
},
components:{
'select2': Select2
},
select.vue
<template>
<select multiple class="input-sm" :name="name" id="select2-template">
<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{
props: ['options', 'value', 'name'],
template: '#select2-template',
data(){
return{
msg: 'hello vue'
}
},
mounted(){
var vm = this;
$(this.$el)
.select2({theme: "bootstrap", data: this.options})
.val(this.value)
.trigger('change')
.on('change', function () {
vm.$emit('input', $(this).val())
})
},
watch: {
value: function (value) {
if ([...value].sort().join(",") !== [...$(this.$el).val()].sort().join(","))
$(this.$el).val(value).trigger('change');
},
options: function (options) {
$(this.$el).select2({ data: options })
}
},
destroyed: function () {
$(this.$el).off().select2('destroy')
}
}
</script>
php code sub.php
'selected' => $model->Users()->where('role', 'TE')
->orderBy('name')
->get(),
'options' => User::where('role', 'TE')
->orderBy('name')
->get()