Vue js how to use props values to v-model

Viewed 7895

I have two component namely App.vue and hello.vue

In App component I import the hello component and use props to pass relevant data to the hello component. there I bind data which are took from the App component.

In my hello component I have a input box bind to the passed value.

My final goal is pass values as props to the hello component and change it and finally pass that edited values to the backend using the save method.

How do I achive this?

This is what I have done up to now.

App.vue

<template>
  <div id="app">
    <hello-world :msg="'hello good morning'"></hello-world>
  </div>
</template>

<script>
import helloWorld from "./components/HelloWorld";
export default {
  components: {
    helloWorld
  }
};
</script>

hello.vue

<template>
  <div>
    <input type="text" :value="msg">
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  props: {
    msg: String
  }
};
</script>

In my hello component's input field v-model is not possible. I want something similar to the v-model.

1 Answers

You cannot use prop to bind to v-model. Child component is not supposed to modify prop passed by the parent component.

You will have to create a copy of prop in your child component if you wish to use prop with v-model and then watch prop like this:

<template>
    <div>
        <input type="text" @input="onInput" v-model="msgCopy">
    </div>
</template>

<script>
export default {
    name: "HelloWorld",
    props: {
        msg: String
    },

    data() {
        return { msgCopy: '' };
    },

    methods: {
        onInput(newInputValue) {
            this.$emit('msgChange', newInputValue);
        }
    }

    watch: {
        msg(newVal) {
            this.msgCopy = newVal;
        }
    }

};
</script>

Also, notice the use of event handler @input to pass changed prop back to the parent component via event. As a syntax sugar, you can make your Hello component work as a custom form input control by adopting to v-model lifecycle.

Related