首页 > 解决方案 > 如何在兄弟提交上呈现 vuejs 组件

问题描述

我有以下代码

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


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

文件管理组件代码:

<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>


附件列表组件代码:

<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>

我想要做的是,当我在另一个组件中单击保存时(在发布请求完成后),我希望能够加载列表的表格。我将如何实现这一目标?

标签: javascriptvue.jsvuejs2axios

解决方案


最简单的方法是让您的FileManagement组件发出一个父级可以监听的事件,然后触发该AttachmentList#getList()方法。

例如

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

并在父模板中

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

推荐阅读