Steps for preloading images in nuxt-dropzone1. Begin by importing the

I am currently utilizing nuxt-dropzone https://www.npmjs.com/package/nuxt-dropzone for image uploads. My goal is to also utilize it as an image library where users can view their uploaded images in a similar fashion. As there isn't much documentation available for nuxt-dropzone, I am curious about how to preload the images into the dropzone.

Below is the code snippet:

<template>
  <v-card style="border-radius: 0; box-shadow: none" class="px-10">
    <v-row justify="center">
      <div class="pt-8" style="width: 1050px">
        <v-tabs
          :centered="false"
          :hide-slider="true"
          :fixed-tabs="false"
          class="hls-tabs py-1"
          height="100%"
        >
          <v-tab
            :ripple="false"
            class="hls-tab background py-3 tabs-0"
            active-class="primary tab-active"
          >
            <div class="background px-1 tab-container">
              <p class="tab-content py-4 subheading">Upload Image</p>
            </div>
          </v-tab>
          <v-tab
            :ripple="false"
            class="hls-tab background py-3 tabs-1"
            active-class="primary tab-active"
          >
            <div class="background px-1 tab-container">
              <p class="tab-content py-4 subheading">Image Library</p>
            </div>
          </v-tab>
          <v-tab-item class="tab-item tab-item-0">
            <div class="tab-item-content px-15 py-15" style="min-height: 400px">
              <dropzone
                id="imageUpload"
                ref="imageUpload"
                v-model="testImages"
                :options="options"
                :destroy-dropzone="true"
                :style="
                  isUploaded
                    ? 'border: 0; border-radius: 25px'
                    : 'border: 4px dashed rgb(111, 118, 167); border-radius: 25px'
                "
                @vdropzone-file-added="onFileAdded"
                @vdropzone-removed-file="onFileRemove"
              >
                <v-icon size="60" color="rgb(176, 173, 173)" class="pb-5"
                  >mdi-file-upload-outline</v-icon
                >
                <h3 style="color: rgb(111, 118, 167)" class="pb-5">
                  To Upload Media, drag files here
                </h3>
                <h3 style="color: rgb(111, 118, 167)" class="pb-5">OR</h3>
                <h3 style="color: rgb(111, 118, 167)">click to select file</h3>
              </dropzone>
            </div>
          </v-tab-item>
          <v-tab-item class="tab-item tab-item-0">
            <div class="tab-item-content" style="min-height: 400px">
              <dropzone
                id="imageLibrary"
                ref="imageLibrary"
                :destroy-dropzone="true"
                :options="libraryOptions"
              >
                <div
                  v-for="image in testImages"
                  :key="image.dataURL"
                  class="dropzone-previews dropzone"
                >
                  <img :src="image.dataUrl" :height="200" :width="200" />
                </div>
              </dropzone>
        </v-tabs>
      </div>
    </v-row>
  </v-card>
</template>

<script>
import dropzone from 'nuxt-dropzone';
import 'nuxt-dropzone/dropzone.css';
import defaultImage from '~/assets/empty_photo.png';
import second from '~/assets/google_mic.png';

export default {
  name: 'ImageUploadDialog',
  components: { dropzone },
  data() {
    return {
      images: [],
      youtubeUrl: '',
      isUploaded: false,
      testImages: [defaultImage, second],
      options: {
        url: 'https://httpbin.org/post',
        addRemoveLinks: true
      },
 libraryOptions: {
        url: 'https://httpbin.org/post'
      }
    };
  },
  methods: {
    handleClose() {
      this.$nuxt.$emit('close-image-upload');
    },
    handleSave() {
      for (const file of this.$refs.imageUpload.dropzone.files) {
        this.images.push(file);
      }

      const lastIndex = this.youtubeUrl.lastIndexOf('/');
      const youtubeIdentifier = this.youtubeUrl.slice(lastIndex + 1);
    },
    onFileAdded() {
      this.isUploaded = true;
    },
    onFileRemove() {
      if (this.$refs.imageUpload.dropzone.files.length === 0) {
        this.isUploaded = false;
      }
    }
  }
};
</script>

I have attempted to use the "instance" to emit during loading, but I consistently encounter an error indicating that the property of dropzone cannot be read.

  mounted() {
    const instance = this.$refs.imageLibrary.dropzone;
    for (const image of this.testImages) {
      const mockFile = { name: image, size: 12345 };
      instance.emit('addedFile', mockFile);
    }
  },

Answer №1

Implementing the dropzone.js manuallyAddFile() method and using nextTick ensures that uploaded images are displayed correctly.

mounted(){
      this.$nextTick(() => {
          for(const image of this.testImages){
            let url = `${imageLink}`;
            let file = { size: 123, name: image, type: "image/png" };
            this.$refs.myVueDropzone1.manuallyAddFile(file, url); 
         }
      });       

}

Answer №2

What I discovered was that the dropzones were not functioning properly because they were being loaded before they were actually displayed on the screen. The references only worked once the dropzone was visible. To fix this issue, I used a 'window.setTimeout' to ensure the refs worked correctly. Ultimately, I decided to move the second dropzone into its own component for better organization.

The new component structure looked like this:

<template>
  <div class="tab-item-content" style="min-height: 400px">
    <dropzone
      id="imageLibrary"
      ref="imageLibrary"
      :destroy-dropzone="true"
      :options="libraryOptions"
    >
    </dropzone>
  </div>
</template>

<script>
import dropzone from 'nuxt-dropzone';
import 'nuxt-dropzone/dropzone.css';
import defaultImage from '~/assets/empty_photo.png';
import second from '~/assets/google_mic.png';
export default {
  name: 'ImageLibrary',
  components: { dropzone },
  data() {
    return {
      testImages: [defaultImage, second],
      libraryOptions: {
        url: 'https://httpbin.org/post'
      }
    };
  },
  mounted() {
    for (const image of this.testImages) {
      console.log('image', image);
      const url = `${image}`;
      const file = { size: 123, name: `${image}`, type: 'image/png' };
      this.$refs.imageLibrary.manuallyAddFile(file, url);
    }
  }
};
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Vue 3 Components Failing to Render

After spending the past 5 hours troubleshooting, I am still unable to pinpoint the issue with my current setup. Essentially, what I am trying to achieve is to have a central "wrapper" application that loads my common codebase, which happens to be a Vue co ...

Converting an object to an array with the help of jQuery

I have been working with a json file and created an object using jquery's $.get method. Here is what it looks like when I log it: console.log(array); [Object, Object, Object, Object, Object, Object, Object, Object] 0 : Object country ...

Which HTTP headers pertain to the loading of iframes? nuxt-helmet

Can anyone explain which security headers are associated with iframe loading issues and may prevent the iframe from being loaded? I implemented nuxt-helmet to configure security headers in my nuxt project. However, after uploading my site to a server loca ...

Button click not triggering JQuery click event

$(document).ready(function () { $('#btnApplyFilter').click(function () { alert("JQuery is not running!"); }); }); Why is the above function not working when the button is clicked? Here is the code for my button : ...

Is there a way to create a miniature camera or map within a scene in three.js without cropping the viewport?

Is there a way to create a mini-map or mini-cam using three.js? The idea is to have two camera views - one mini-map or "mini-cam" in the top right corner (as shown in the image) and the main camera view covering the rest of the scene without the border. ...

Tips for designating all content within a <div> element to open in a blank target (target="_blank")

I am looking to open all content within a specific <div> in a new tab (target="_blank"). I am open to any solution, whether it involves JS, CSS, HTML, classes, IDs, etc. I experimented with using <base target="_blank">, but it affect ...

I am facing an issue with installing bcrypt npm package. The error message is showing up as "Error: Cannot locate module node-pre-gyp

Currently using Windows 10 (version 10.0.17763 build 17763) and attempting to install Bcrypt with Nodejs Express server via NPM. Freshly updated to the latest version of Nodejs (v12.16.3). Regardless of whether I try installing the most recent edition of B ...

How can you correctly make an Ajax request using computed properties sourced from VueX Store?

Is there a way to make an AJAX call where one of the parameters is a computed State in VueX? For instance, if I use this.$axios.get('someUrl/' + accID ), with accID being a computed property from VueX (using MapState), sometimes it returns ' ...

What is the functionality of the "respond_with_navigational" feature?

Currently, I am integrating Devise and DeviseInvitable to handle authentication in my application. However, I'm facing challenges when trying to incorporate AJAX functionality into InvitationsController#update. The structure of the controller in Devis ...

It is impossible to perform both actions at the same time

Is it possible to create a progress bar using data attributes in JQuery? Unfortunately, performing both actions simultaneously seems to be an issue. <div class="progressbar"> <div class="progressvalue" data-percent="50"></div> </d ...

What is the process for configuring SSL in node.js and express.js?

I'm currently working on setting up my application to run in HTTPS mode. Despite thinking that my configuration is correct, the page isn't loading at all. Within my SSL folder, I have the following files: credentials.js my-ca.pem my-cert.pem my ...

Using Leaflet to beautify categorical json information

As a beginner in coding, I must apologize if a similar question has already been asked. I've spent days searching but haven't found the right combination of terms to find examples for my scenario. I am exploring various small use cases of differ ...

Extract the chosen option from a dropdown menu, and then transfer it to another dropdown menu with a new corresponding value

Below is a select box I currently have: <td align="center"> <select id="selectW" name="type" onChange="this.form.submit()"> <option value="select...">select</option> <option value=" ...

Making changes to the res object in an Express.js application

I came up with an innovative idea for the backend design of my single-page application website. My plan is to configure it so that any routes starting with "/api/" will return only the necessary data in JSON format, while all other routes will trigger a fu ...

I continually run into the error message "Uncaught ReferenceError: dropMenu is not defined" and "Uncaught TypeError: Cannot read property 'style' of null."

I'm attempting to create a navigation bar with submenus, but I keep encountering errors such as "dropMenu is not defined" and "Uncaught TypeError: Cannot read property 'style' of null" when hovering over the Paris links. Any thoughts on what ...

Odd behaviour when using JSON in CouchDB

I have developed an updates handler in CouchDB with test code like this (before inserting into Couch I am removing newlines): function (doc, req) { if (req['userCtx']['roles'].indexOf('editor') < 0) { return [ ...

What is the best method for enabling HTML tags when using the TinyMCE paste plugin?

After spending countless hours searching for a solution, I am still puzzled by this problem. My ultimate goal is to have two modes in my powerful TinyMCE editor: Allowing the pasting of HTML or Word/OpenOffice text with all styles and formatting attribu ...

Underscore - Evaluating the differences between two arrays of objects (positions)

Is it possible to compare arrays based on the changes in their element positions? I have an original array of objects that has one of its elements' values changed, resulting in a new array: origElements = [{id: 1, value: 50}, ...

What is preventing jQuery 3 from recognizing the '#' symbol in an attribute selector?

After updating my application to jQuery 3, I encountered an issue during testing. Everything seemed to be working fine until I reached a section of my code that used a '#' symbol in a selector. The jQuery snippet causing the problem looks like th ...

The issue of duplicate items being stored in an array arose when inserting a new element

I am new to angular and currently working on an application that allows users to take notes and store them in a database. However, I have encountered a problem during the note addition process. When there are no existing notes in the database and I add tw ...