[Vuejs]-Vue/Jquery override two-way data bidning

2👍

The best way if you really are stuck would be to add an event listener in your vue model:

var app = new Vue({
  el: '#root',
  data: {
    name: '',
    email: '',
  },
  methods: {
    proceed: function () {

    },
    foo : function(event){
        this.email = event.target.value;
    }
  },
});

<input @change="foo" type="text" name="email" id="email" v-model="email">

This way, you don’t have to modify the jQuery logic.

Updated jsfiddle: https://jsfiddle.net/s3b7f1ah/1/

👤Axnyff

1👍

Change you jquery code to set the model value instead and it will get reflected in the input field.

 //jQuery
 $(function() {
       $('#push-email').click(function() {
           app.email = 'john@example.com';
       });
 });
👤RonC

0👍

You could write a directive to handle the jQuery change (as long as jQuery issues one). If jQuery just sets the value without triggering a change event, you’ll never see it. Borrowing code from Axnyff:

//Vue
var app = new Vue({
  el: '#root',
  data: {
    name: '',
    email: '',
  },
  methods: {
    proceed: function() {

    },
    foo: function(event) {
      this.email = event.target.value;
    }
  },
  directives: {
    onJqueryChange: {
      bind(el, binding) {
        $(el).change(binding.value);
      }
    }
  }
});


//Jquery
$(function() {
  $('#push-email').click(function() {
    $('#email').val("john@example.com").change();
  });
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="push-email">Fill in email</button>
<br>
<br>
<div id="root">
  <label for="name">Name</label>
  <input type="text" name="name" id="name" v-model="name">

  <label for="name">Email</label>
  <input v-on-jquery-change="foo" type="text" name="email" id="email" v-model="email">
  <br>
  <br>
  <button @click="proceed">next</button>
  <br>
  <br> {{ name }}
  <br> {{ email }}
</div>
👤Roy J

Leave a comment