moses toh
moses toh

Reputation: 13172

How can I send property to value of input text ? (Vue.JS 2)

My component is like this :

<template>
    <div class="modal" tabindex="-1" role="dialog">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <form id="form-message">
                    ...

                    <input type="text" class="form-control" id="subject" placeholder="Subject" v-model="product_name" required>
                    ...   
                </form>    
            </div>
        </div>
    </div>         
</template>

<script>
    export default {
        name: 'MessageModal',
        props: ['productName'],
        data() {
            return {
                product_name: this.productName,
            }
        }
    }
</script>

This component is a modal. This modal showed when click a button. When the modal component showed, I want send value of product_name property to value of input text

I try like above code, but the input text not display value of product_name property

If I put input text out the form like this :

<input type="text" class="form-control" id="subject" placeholder="Subject" v-model="product_name" required>
<form id="form-message">
    ...
</form>    

It works. But why If I put input text in the form, it does not work?

How can I solve it?

Upvotes: 2

Views: 1766

Answers (1)

peaceman
peaceman

Reputation: 1721

I would do it like this:

<template>
...
    <input type="text" class="form-control" id="subject" placeholder="Subject" v-model="pname" required>
...                
</template>

<script>
  export default {
    mounted() {
      this.pname = this.productName
    },
    props: ['productName'],
    data() {
        return {
            pname: "",
        }
    }
  }
</script>

This way when component is mounted you set prop to internal data property pname of component and bind value of input field with pname.

Upvotes: 1

Related Questions