Cornwell
Cornwell

Reputation: 3410

Unable to show updated v-model value in input

I have the following code:

const BasicInput = {
  template: '<input v-model="content" @input="handleInput" />',
  prop: ["value"],
  data() {
    return {
      content: this.value
    };
  },
  methods: {
    handleInput(e) {
      this.$emit("input", this.content);
    }
  }
};

new Vue({
  el: "#app",
  data: { name: "" },
  mounted() {
    self = this;
    setTimeout(() => {
      self.name = "test";
    }, 2000);
  },
  components: { BasicInput }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <basic-input v-model="name"></basic-input>
  <p>
    <strong>Name:</strong> {{ name }}
  </p>
</div>

How do I get the updated v-model value to also show in the input tag ?

Upvotes: 1

Views: 220

Answers (1)

vahdet
vahdet

Reputation: 6749

You need to v-bind the property for the BasicInput component. The short form of it is :.

See <basic-input :value="name"></basic-input> usage below, only changed it.

const BasicInput = {
  template: '<input v-model="content" @input="handleInput" />',
  prop: ["value"],
  data() {
    return {
      content: this.value
    };
  },
  methods: {
    handleInput(e) {
      this.$emit("input", this.content);
    }
  }
};

new Vue({
  el: "#app",
  data: { name: "" },
  mounted() {
    self = this;
    setTimeout(() => {
      self.name = "test";
    }, 2000);
  },
  components: { BasicInput }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <basic-input :value="name"></basic-input>
  <p>
    <strong>Name:</strong> {{ name }}
  </p>
</div>

Upvotes: 1

Related Questions