arakibi
arakibi

Reputation: 447

2 way binding is not working properly in vuejs

I have defined a vuejs component this way:

<template>
    <form @submit.prevent="submit">
        <textarea id="content" cols="30" rows="10" v-model="content">{{ content }}</textarea>

        <button class="btn btn-lg btn-success" type="submit" @click="send()">
            Send content
        </button>
    </form>
</template>

<script>
    export default {
        data() {
            return {
                content: '// Initial content'
            }
        },
        methods: {
            send() {
                console.log('Content', this.content);
            },
            submit() {
                return false;
            }
        },
        mounted() {
            console.log('Template init ', this.content);
        }
    }
</script>

When I click on send, the send method outputs the content of the textarea as expected. But when I change the content of the textarea with jquery:

$('#content').val(content);

and hit send, it doesn't update content in the template. "Send" outputs the old value.

can somebody please explain to me what's wrong here?

Upvotes: 1

Views: 1021

Answers (1)

austeng
austeng

Reputation: 41

v-model is listening for an input event to trigger changing the value of its bound variable.

From the vue.js documentation:

v-model internally uses different properties and emits different events for different input elements:

  • text and textarea elements use value property and input event;
  • checkboxes and radiobuttons use checked property and change event;
  • select fields use value as a prop and change as an event.

Using the JQuery val() method to select the element and change the value does not trigger an event that v-model is listening for, so the value of your bound variable does not change/update.

If you absolutely have to use JQuery to change the content, you could manually trigger an event that might also trigger the v-model binding to update:

$('#content').val(content).trigger('input');

Upvotes: 1

Related Questions