Search code examples
vuejs2vue-component

Vue js : _this.$emit is not a function


I have created a Vue component called imageUpload and passed a property as v-model like so:

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

and within the imageUpload component I have this code

<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])
         }
    }

and I receive this error:

Uncaught TypeError: _this.$emit is not a function

Thanks


Solution

  • Do not define your method with a fat arrow. Use:

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

    When you define your method with a fat arrow, you capture the lexical scope, which means this will be pointing to the containing scope (often window, or undefined), and not Vue.