简体   繁体   中英

How to render vuejs component on sibling submit

I have the following code

<body>
   <div class="content" id="app">
      <file-management></file-management>
      <attachment-list></attachment-list>
   </div>


   <script src="{{ asset('js/app.js') }}"></script>
</body>

FileManagement component code:

<template>
    <div>
        <button type="button" @click="storeList()">
            Save
        </button>
    </div>
</template>


<script>
    export default {
        methods: {
            storeList: function () {
                axios.post('/list', this.data, config)
                    .then(() => {
                      // on save I want to be able to load the table again that is found in AttachmentList component  
                    });
            },
        }
    }
</script>


AttachmentList component code:

<template>
    <div>
        <tr v-for="attachment in attachments" :key="attachment.id">
            <td>{{ attachment.name }}</td>
        </tr>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                attachments: []
            }
        },
        methods: {
            getList() {
                axios.get(`/list`)
                    .then((data) => {
                        this.attachments = data;
                    });
            }
        }
    }
</script>

What I want to do is that I want to be able to load the table of the list when I click save in the other component (after the post request has completed). How will I be able to achieve this?

Easiest way would be to have your FileManagement component emit an event which the parent can listen to, then trigger the AttachmentList#getList() method.

For example

// in AttachmentList
methods: {
  async storeList () {
    await axios.post('/list', this.data, config)
    this.$emit('list-updated')
  }
}

and in the parent template

<file-management @list-updated="$refs.list.getList()"></file-management>
<attachment-list ref="list"></attachment-list>

This is how I would proceed.

  • create a parent component for the siblings.
  • add a boolean data member (flag) to it with the status of the clicked button.
  • emit a signal from FileManagement when the button is clicked.
  • catch this signal in the parent component to set the flag.
  • pass this flag to the AttachmentList component as a prop.
  • use this flag inside a v-if to show / hide the the table.

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