首页 > 解决方案 > 使用 vuejs 将数据变量从子级发送到父级

问题描述

我有一个模态组件(称为子组件modal_form.vue),我在另一个组件中调用它index.vue

我想从 to 发送一个数据modal_form.vue变量index.vue

有人可以给我一个例子吗?

PS:modal_form包含一个 axios 请求,所以我想将响应发送到index.vue

-- 模态 --

methods: {
    post() {
        getAPI.post('api/contact/', this.form)
        .then(response => (this.data = response.data))
        .then(() => (this.$emit('dataLoaded', this.data)))
        .catch(error => console.log(error.response))
    }
}

- 指数 -

<addContactModal v-if="openContactModal" :dataLoaded="refreshContactList"></addContactModal>

data: function(){
    return {
        openContactModal: true,
        contacts: []
    }
},
methods: {
    refreshContactList(data){
        this.contacts = JSON.parse( JSON.stringify( data ) )
    },
}

标签: vue.js

解决方案


如果我正确理解您的问题,您可以使用自定义事件从 Vue 中的子组件发射到父组件。

https://vuejs.org/v2/guide/components-custom-events.html

  1. 下面的示例显示modal_form.vue包含一个按钮,单击该按钮将运行方法grabDataAndEmit

  2. grabDataAndEmit使用 ES8 await 语法进行 axios 调用。然后将响应存储在一个变量中,并通过此代码段将其发送给父级this.$emit( 'handle-form-data', response );

  3. 可以看到父index.vue处理了这段代码中的事件,@handle-form-data="handleFormDataCallback"其中@handle-form-data是被监听的事件,传入的值是该事件的处理程序/回调。

注意: @ 只是 v-on 的缩写:

<!-- modal_form.vue  -->
<template>
    <div>
        <div @click="grabDataAndEmit">button</div>
    </div>
</template>
<script>
import axios from 'axios';
export default {
    methods: {
        async grabDataAndEmit() {
            const response = await axios.get('/api/some/data');
            this.$emit( 'handle-form-data', response );
        }
    }
}
</script>

<!-- index.vue  -->
<template>
    <div>
        <!-- @handleFormData listens for "handleFormData" event to be $emit from the child.  -->
        <modal-form @handle-form-data="handleFormDataCallback" />
    </div>
</template>
<script>
import ModalForm from './modal_form.vue';
import axios from 'axios';
export default {
    components: { ModalForm },
    methods: {
        handleFormDataCallback( $event ) {
            // Do something with the $event data emitted.
            // $event in this case is equal to "response" from the child component.
            console.log( $event )
        }
    }
}
</script>

我希望这个答案对您手头的任务有所帮助!


推荐阅读