How to get which component called the event in Vue/Nuxt?

Viewed 120

I am trying to build an app that allows a user to create multiple items and upload images for each item.

I am using Vux Uploader for uploading images like this

<div
  v-for="(variant, variantId) in variants"
  :key="variantId"
  class="position-relative mb-2 bg-white rounded-lg border p-4"
>

  <uploader
    v-model="variant.imagesList"
    name="files"
    :url="uploadUrl"
    limit="5"
    @on-change="onChange"
    @on-cancel="onCancel"
    @on-success="onSuccess"
    @on-error="onError"
    @on-delete="onDelete"
  ></uploader>
</div>
<button @click="addVariantComponent"></button>

data() {
  return {
    uploadUrl: 'http://localhost:1337/upload/',
    variants: [],
  }
},

methods: {
  addVariantComponent() {
    const variant = {
      id: this.variants.length + 1,
      images: [],
      imagesList: [],
      cost: '',
      product_code: '',
      stock: '',
    }

    this.variants.push(variant)
  },

  onChange(fileItem, fileList) {
    console.log('on-change: ', fileItem, fileList)
  },
  onCancel() {
    console.log('on-cancel: Sucess')
  },
  onSuccess(res, fileItem) {
    console.log('on-success: ', res)
    console.log(fileItem)
    // variant.images.push(res[0].id)
  },
  onError(res) {
    console.log('on-error: ', res)
    this.$showToast(res.statusText, 'danger')
  },
  onDelete(deleteItem, cb) {
    // setTimeout(() => {
    console.log('on-delete: ', deleteItem)
    cb && cb()
    // }, 3000);
  },
},

A user can click a Create new button and add another variant

Now my question is how do I get the variant for which the image was uploaded?

I am able to upload the images, but I need to attach the id of the uploaded image with the right variant?

Thanks.

1 Answers

Just pass variant as an argument to the event handler function. You'll have to wrap it in another function since it looks like that event emits multiple arguments.

@on-success="(res, fileItem) => onSuccess(res, fileItem, variant)"
onSuccess(res, fileItem, variant) {
  // ...
}

For events that emit only a single argument, you can use this syntax instead (where $event is the argument):

@on-error="onError($event, variant)"

See the docs for v-on.

Related