Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change event doesn't activate with VueJS 2 using Materialize CSS Select component

I'm trying to make cascading combo-boxes, and stuck with a problem: VueJS doesn't see change event of Materialize select element. Here is my code:

let app = new Vue({
  el: '#app',
  data: {
    elements: [
      {'id' : 1, 'text' : 'Option 1'},
      {'id' : 2, 'text' : 'Option 2'}
    ]
  },

  updated() {
    $('select').material_select();
  },

  methods : {
    onChange() {
      alert('Option changed!');
    }  
  }
});

$('select').material_select();
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/js/materialize.min.js"></script>
<script src="https://unpkg.com/vue"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css" rel="stylesheet"/>

<div class="container" id="app">
  <div class="row">
    <div class="input-field col s12 m6">
      <select name='somename' id='somename' @change='onChange()'>
        <option selected="" disabled="" value="">Choose your make</option>
        <option v-for="option in elements" :value="option.id">{{option.text}}</option>
      </select>
      <label>Car make</label>
    </div>
  </div>

  <select class="browser-default" name='somename' id='somename' @change='onChange()'>
    <option selected="" disabled="" value="">Choose your make</option>
    <option v-for="option in elements" :value="option.id">{{option.text}}</option>
  </select> 
</div>

If changing JS code to handle the 'change' event with jQuery - it works.

$('#somename').on('change', function(){alert('Changed - JQUERY')});

Really, don't understand what's the problem here. If executing that vue code on plain html components - it also works.

like image 374
Sergiu Avatar asked Nov 09 '17 12:11

Sergiu


1 Answers

When you use jquery and vue like this case the manipulation of DOM is done by jquery, so you would 'emit' an event to vue, then vue can realize the changes in te view or his values. Sorry for my bad english.

Here some example in documentation of vue and codepen

 mounted() {
    var self = this;//vue
      $('#vueSelect').material_select();
      $('#vueSelect').on('change', function () {            
        console.log("Change from Wrapper!", this.value)
        self.$emit("change", this.value)
      });
    self.$on("change", function(data){
       console.log('Option changed!', data);
      this.selected = data
    });       
  }
like image 188
panicoper Avatar answered Sep 20 '22 00:09

panicoper