aletede91
aletede91

Reputation: 1166

Update Vue model from jQuery

This is my Vue code:

<div id="root">
    <input v-model="title" name="title" />
    <div class="my-title">{title}</div>
</div>

I need to change the input value after a click on a button in jQuery (I can't change this part), something like:

$('.button').on('click', function() {
    $("input[name='title']").val('some new value');
});

This works as expected, the input value showed in the browser is now some new value but the message in my-title div is not updated.

Any ideas about how to update it?

Upvotes: 4

Views: 2387

Answers (3)

Dawid Zbiński
Dawid Zbiński

Reputation: 5826

By default, v-model on text inputs listens to native input events in order to synchronise the view-model. You can set the value as you did and then just trigger native input event in order to update the value in model.

$('.button').on('click', function() {
  
  // Find inputs
  const input = $("input[name='title']");

  // Set value
  input.val('some new value');

  // Create native event
  const event = new Event('input', { bubbles: true });

  // Dispatch the event on "native" element
  input.get(0).dispatchEvent(event);
});

Here's a working fiddle: https://jsfiddle.net/548jofad/

Upvotes: 11

yooneskh
yooneskh

Reputation: 813

If you have a reference to the vue app, you can easily set it.

const app = new Vue({ ... });

$(....).click(() => {
  app.title = 'whatever';
})

Upvotes: 0

Igor Moraru
Igor Moraru

Reputation: 7729

You could dispatch customEvents to window object, and then listen to those events in Vue component. See the working snippet.

const app = new Vue({
el: "#app",
data: {
  title: "title"
  },
created(){
   window.addEventListener('updateInput', (event) => {
       this.title = event.detail
   });
  }
})

$('.button').on('click', function() {
    window.dispatchEvent(new CustomEvent("updateInput", { detail: 'some new title' } ) );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
    <input v-model="title" name="title" />
    <div class="my-title">{{title}}</div>
</div>

<button class="button">Button</button>

Upvotes: 2

Related Questions