Vue js:_this.$ emit不是函数

Bar*_*rki 14 vue-component vuejs2

我创建了一个Vue组件调用imageUpload并将属性作为v-model传递

<image-upload v-model="form.image"></image-upload>

imgeUpload组件中我有这个代码

<input type="file" accept="images/*" class="file-input" @change="upload">

upload:(e)=>{

    const files = e.target.files;
    if(files && files.length > 0){
        console.log(files[0])
        this.$emit('input',files[0])
     }
}    
Run Code Online (Sandbox Code Playgroud)

我收到了

未捕获的TypeError:_this.$ emit不是函数

谢谢

Ber*_*ert 29

不要使用胖箭头定义您的方法.使用:

upload: function(e){
    const files = e.target.files;
    if(files && files.length > 0){
        console.log(files[0])
        this.$emit('input',files[0])

    }
} 
Run Code Online (Sandbox Code Playgroud)

当您使用粗箭头定义方法时,您将捕获词法范围,这意味着this将指向包含范围(通常window,或undefined),而不是Vue.


Rya*_*yer 6

如果 $emit 不在 的当前上下文/引用上this,也许当您处于Promise 的then或方法中时,就会出现此错误。在这种情况下,捕获对Promise 外部的catch引用,然后使用,以便调用成功。this$emit

<script type="text/javascript">
var Actions = Vue.component('action-history-component', {
        template: '#action-history-component',
        props: ['accrual'],
        methods: {
            deleteAction: function(accrualActionId) {
                var self = this;
                axios.post('/graphql',
                    {
                        query:
                            "mutation($accrualId: ID!, $accrualActionId: String!) { deleteAccrualAction(accrualId: $accrualId, accrualActionId: $accrualActionId) { accrualId accrualRate name startingDate lastModified hourlyRate isHeart isArchived minHours maxHours rows { rowId currentAccrual accrualDate hoursUsed actions { actionDate amount note dateCreated } } actions {accrualActionId accrualAction actionDate amount note dateCreated }} }",
                        variables: {
                            accrualId: this.accrual.accrualId,
                            accrualActionId: accrualActionId
                        }
                    }).then(function(res) {
                    if (res.data.errors) {
                        console.log(res);
                        alert('errors');
                    } else {
                        self.$emit('accrualUpdated', res.data.data.deleteAccrualAction);
                    }
                }).catch(function(err) {
                    console.log(err);
                });
            }
        }
    });
Run Code Online (Sandbox Code Playgroud)