【问题标题】:Send data variable from child to parent using vuejs使用 vuejs 将数据变量从子级发送到父级
【发布时间】:2021-06-19 18:26:03
【问题描述】:

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

我想将一个数据变量从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


【解决方案1】:

如果我正确理解了您的问题,您可以使用 自定义事件 在 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>

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

【讨论】:

  • 我使用了您的代码,唯一的问题是我尝试刷新联系人变量,我这样做了。但我的 v-for 联系人中的联系人。未刷新
  • 你能帮我更新我的联系人变量吗,我已经这样做了,this.contacts = $event 但我的 v-for 没有刷新
  • 嗯,我假设你的 $event 是一个对象数组?也许尝试做this.contacts = JSON.parse( JSON.stringify( $event ) )
  • 同样的问题,我会更新我的问题,你可以看到我的代码;)
  • 已修复:而不是 @
【解决方案2】:

如果您不想使用$emit 和事件,使用Vuex 有一种更简单的方法。 您应该像下面的指南一样定义您的商店,然后在您的模态中使用突变来设置新数据,并在您说需要模态数据的 index.vue 等其他组件中使用商店状态。这里只是介绍Vuex的最简单的商店

npm install vuex --save

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  }
})

现在,您可以通过 store.state 访问状态对象,并使用 store.commit 方法触发状态更改:

store.commit('increment')

console.log(store.state.count) // -> 1

为了在你的 Vue 组件中访问 this.$store 属性,你需要将创建的 store 提供给 Vue 实例。 Vuex 有一种机制可以使用 store 选项将 store 从根组件“注入”到所有子组件中:

new Vue({
  el: '#app',
  store: store,
})
methods: {
  increment() {
    this.$store.commit('increment')
    console.log(this.$store.state.count)
  }
}

注意,如果你有一些 Axios 调用或异步操作,你必须使用 actions 对象而不是 mutations 对象来定义你的函数。 请参阅以下代码:

您的商店架构:

state : {
    APIData : null
}

mutations : {
    setAPIData(state, newData) {
        state.APIData = newData
    }
}

在你的 Vue 实例中:

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

在您的另一个组件中,您可以使用 this.APIData 作为计算属性来访问新数据:

    computed : {
        APIData(){
            return this.$store.state.APIData
        }
    }

【讨论】:

    猜你喜欢
    • 2019-08-22
    • 2018-05-17
    • 2023-03-04
    • 2023-03-03
    • 2020-07-01
    • 2016-11-14
    • 1970-01-01
    • 1970-01-01
    • 2021-05-27
    相关资源
    最近更新 更多