简体   繁体   中英

How can i pass data from parent component to a child component in Vue.js?

I am new in Vue.js i don't know how can i pass data from parent component to child component on click. I tried with props but it did not worked. So i have a modal and i wanna pass data to it when i open it on click.

Button

<div class="m-widget14__header_menu">
   <button v-on:click="doSomethingWith" type="button" class="btn btn-accent btn-md m-btn m-btn--icon m-btn--icon-only m-btn--pill" data-toggle="modal" data-target="#createContactModal"><i class="la la-plus"></i></button>
</div>

Parent script

<script>
import ContactModalCreate from './ContactModalCreate.vue'
export default {
  data () {
    return {
      footer: [], 
      user: null
    }
  },
  methods: {
    doSomethingWith(user) {
        this.user = {name: 'Mario'}
        console.log('user', this.user)
    }
  },
  components: {
    'contact-modal-create': ContactModalCreate
  }
}
</script>

Child component, for now i just wanna set the name in header for example.

<h5 class="modal-title" id="createContactModalLabel">{{ user.name }}</h5>

<script>
export default {
  props: ['user'],
  data () {
    return {
    }
  },
}
</script>

So i imported the child component in the parent component, and the child component is called then right? So can anyone help me please?

Thanks.

Add the prop in your modal declaration.

Somewhere in parent template:

<div class="m-widget14__header_menu">
   <button v-on:click="doSomethingWith" type="button" class="btn btn-accent btn-md m-btn m-btn--icon m-btn--icon-only m-btn--pill" data-toggle="modal" data-target="#createContactModal"><i class="la la-plus"></i></button>
</div>

<contact-modal-create :user="user"></contact-modal-create>

Notice the addition of :user="user" above.

And in your Child component , add a v-if , because user doesn't always have a name (it can be null , as it is when the parent initializes - see parent's data() { ..., user: null } ):

<h5 class="modal-title" id="createContactModalLabel">
    <span v-if="user">{{ user.name }}</span>
</h5>

If you don't add this v-if , you'll get an exception when the page loads (again, because user is initialized as null and null has no name property).

You should simply try this :

data () {
    return {
        footer: [], 
        user: { name: '' }
    }
},

Read more about Reactivity and How Changes Are Tracked .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM