事件发射器参数未定义为侦听器Vue js

问题描述 投票:0回答:1

我对Vue.js很新。我的Laravel项目中有3个简单的组件,一个发布推文的PostForm,以及其他在时间轴上显示帖子的组件。我正在使用Axios发布并从后端获取数据。当我发布推文时,它会被保存在我的数据库中,但是当我按事件传递数据时,我收到此错误。

enter image description here

PostForm组件:

<template>  
    <form action="#" class="form-vertical" @submit.prevent="post">
        <div class="form-group">
            <textarea name="body" id="" cols="30" rows="3" class="form-control" placeholder="Write something likable" v-model="body"></textarea>  
        </div>
        <button type="submit" class="btn btn-primary">Post it!</button>
    </form>
</template>

<script>
import eventhub from '../event'
export default{
    data(){
        return{
            body:null
        }
    },
    methods:{
        post(){

            axios.post('posts',{
                body:this.body
            }).then((response)=>{

            eventhub.$emit('post-added', response.body)
                this.body=null
            })
        }
    }
}
</script>

当我console.log(response.data)我正在得到一切正确...

enter image description here

...然后我将事件(后添加)发送到我的时间轴组件。

时间表组件:

<template>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">Timeline</div>
                    <div class="card-body">
                        <postform></postform>
                        <hr>
                        <post v-for="post in posts" :post="post" :key="post.index"></post>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import eventhub from '../event'
import Post from './Post.vue' 
import postform from './PostForm.vue'

export default {
    data(){
        return{
            posts:[]
        }
    } ,
    components:{
        Post,postform
    }
    ,
    methods:{
        addpost(record){

        }
    },
    mounted() {
        eventhub.$on('post-added',this.addpost)
        axios.get('/posts').then((response)=>{
            this.posts=response.data
        })
    }
}
</script>

我在mount中捕获了后添加的事件,然后将值传递给addpost方法(记录)。这是我收到此错误的地方。

https://snag.gy/Cjlaw6.jpg

在addpost方法当我尝试console/log(record)它给我未定义。我认为这是错误,我不知道为什么它给我未定义。

https://snag.gy/Hz1Xo3.jpg

在我的event.js文件中注意我正在导入只有这个代码module.exports = new Vue()

vue.js vuejs2
1个回答
0
投票

在下面的代码中:

eventhub.$emit('post-added', response.body)

response.bodyundefined。这是因为body不是请求响应中公开的字段(此响应模式特定于axios客户端。)1

假设在发出HTTP POST请求后,服务器返回您要在客户端中处理的响应。

可以以下列方式在响应的data字段中检索该响应数据。

eventhub.$emit('post-added', response.data)
© www.soinside.com 2019 - 2024. All rights reserved.