vue.js - 使用 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 中的子组件发射到父组件。
https://vuejs.org/v2/guide/components-custom-events.html
下面的示例显示modal_form.vue包含一个按钮,单击该按钮将运行方法grabDataAndEmit。
grabDataAndEmit使用 ES8 await 语法进行 axios 调用。然后将响应存储在一个变量中,并通过此代码段将其发送给父级
this.$emit( 'handle-form-data', response );
。可以看到父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>
我希望这个答案对您手头的任务有所帮助!
推荐阅读
- google-admin-sdk - 未找到域
- java - 为什么 Arrays.asList(null) 会抛出 NullPointerException 而 Arrays.asList(someNullVariable) 不会?
- wpf - 如何将对话窗口定位在当前屏幕的左上角?
- laravel - 如何在不同的选项卡中加载不同的数据表?
- r - 如何按纬度过滤 sf 对象?
- javascript - SugarCRM 旧版 (v6) 中的自定义验证
- python - python中的简单迭代
- authentication - 资源“此处的 GUID 值”不存在或其查询的引用属性对象之一不存在
- r - 如何根据小部件输入向表中添加行?
- python - 是否有任何用于记录 python selenium 测试并获取视频或录制的 gif 作为输出的代码?