Apply plugin Select2 with vue.js

1

I'm trying to apply the plugin Select2 on a select I charge it using VUE.JS (I do a v-for on the% option select )

If I do not apply the plugin, by doing v-model="modelo" , I can use the variable ({{modelo}}) correctly.

But if I apply the plugin, VUE stop reading the v-model and I can not use the databinding .

I attach the JSFIDDLE:

link

Code:

var vm = new Vue({
  el: "#divMain",
  data: {
    selected: 'A',
    options: [
      { text: 'One', value: 'A' },
      { text: 'Two', value: 'B' },
      { text: 'Three', value: 'C' }
    ]
  }
});

$('#miSelect').select2({
    placeholder: 'Select an option'
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.1/vue.min.js"></script>
<link href="https://rawgit.com/select2/select2/master/dist/css/select2.min.css" rel="stylesheet"/>
<script src="https://rawgit.com/select2/select2/master/dist/js/select2.js"></script>
<div id="divMain">

  <select id="miSelect" v-model="selected">
    <option v-for="opt in options" v-bind:value="opt.value">
      {{ opt.text }}
    </option>
  </select>
  <span>Selected: {{ selected }}</span>

</div>
    
asked by Migue 11.10.2016 в 20:02
source

1 answer

1

Maybe it's a little "tricky" but here I leave your fiddle modified and working:

var vm = new Vue({
  data: {
    selected: 'A',
    options: [
      { text: 'One', id: 'A' },
      { text: 'Two', id: 'B' },
      { text: 'Three', id: 'C' }
    ]
  },
  mounted() {
  	let self = this; // ámbito de vue
    
    // inicializas select2
    $('#miSelect')
      .select2({ 
      	placeholder: 'Select an option',
      	data: self.options, // cargas los datos en vez de usar el loop
       })
       // nos hookeamos en el evento tal y como puedes leer en su documentación
       .on('select2:select', function () {       
       	var value = $("#miSelect").select2('data');
        // nos devuelve un array
        
        // ahora simplemente asignamos el valor a tu variable selected de VUE
        self.selected = value[0].id
      })
  }
}).$mount('#app');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/select2/select2/master/dist/js/select2.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.1/vue.min.js"></script>
<link href="https://rawgit.com/select2/select2/master/dist/css/select2.min.css" rel="stylesheet"/>

<div id="app">

  <select id="miSelect"></select>
  <span>Selected: {{ selected }}</span>

</div>
    
answered by 14.11.2016 в 02:37