VueJs Send data to modal component

2019-08-09 15:46发布

i want to send my data (first component) to modal (another component). Both component are located in this same place. I need show data to first component data form to my edit modal.

Here is my code:

form.vue :

  <template>
     <tbody v-for="user,index in users">
        <button type="button" class="btn btn-xs" data-toggle="modal" 
         data-target="#editModal"> -> edit button, show modal
     (...)
     <edit-user></edit-user>
    (...)
  </template>

<script>
      components: {
            add: addUser,
            edit: editUser
        },
</script>

edit.vue:

  <template>
    <div id="editModal" class="modal fade" role="dialog">

     <div class="form-group">
        <input type="text" class="form-control" name="nameInput" 
value=" I WANT HERE DATA" v-model="list.name">
                            </div>
(...)
    </template>

How can i do this?

1条回答
甜甜的少女心
2楼-- · 2019-08-09 16:18

A solution would be having the parent component to store the data that both components share.
On the first component you can use $emit to change that data of the parent and then pass that same data to the modal component using props.

Vue.component('app-input', {
  props: ['message'],
  template: `<input type="text" placeholder="Try me" 
  v-bind:value="message"
  v-on:input="$emit('input', $event.target.value)"/>`
});

Vue.component('app-header', {
  props: ['title'],
  template: `<h4>{{title}}</h4>`
});

var app = new Vue({
  el: '#app',
  data: {
    message: ''
  }
});
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
  <app-header v-bind:title="message"></app-header>
  <app-input v-model="message"></app-input>
</div>

The above is a simple example of how it can be done.
The <app-input> component changes the parent message data, and that same property is passed to the <app-header> component as the title.

查看更多
登录 后发表回答