VueJS allows for seamless image uploading using either a gallery of images or input files

Is there a way to enable image selection from "Pick from gallery" feature in addition to the file upload functionality demonstrated in the example below?

I would like the same behavior for selecting an image from the gallery as when uploading a file using input type file.

new Vue({
  el: "#app",
  data: {
        product_image: '',
    product_image_preview: ''
  },
  methods: {
        handleFileUpload(e) {
      const file = e.target.files[0];
      this.product_image = file;
      this.product_image_preview = URL.createObjectURL(file);
    }
  }
})
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

li img{
  width: 80px;
  height: 60px;
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-if="product_image_preview">
    <img :src="product_image_preview" style="width: 100px;height: 100px" />
  </div>
  <div v-else>
    <img src="https://dummyimage.com/100x100/000/fff" alt="">
  </div>
  <hr>
  <label for="product_image">Select Image</label>
  <input type="file" id="product_image" accept="image/*" ref="image" v-on:change="handleFileUpload">
  <h1>OR</h1>
  <h2> Pick From Gallery</h2>
  <div>
    <ul>
      <li>
        <img src="https://images.pexels.com/photos/210186/pexels-photo-210186.jpeg?cs=srgb&dl=time-lapse-photography-of-waterfalls-during-sunset-210186.jpg&fm=jpg" alt="">
        <img src="https://images.pexels.com/photos/733475/pexels-photo-733475.jpeg?cs=srgb&dl=photography-of-night-sky-733475.jpg&fm=jpg" alt="">
        <img src="https://images.pexels.com/photos/982263/pexels-photo-982263.jpeg?cs=srgb&dl=seawaves-on-sands-982263.jpg&fm=jpg" alt="">
      </li>
    </ul>
  </div>
</div>

Answer №1

Arrange your gallery images in an array and when each image is clicked, set the image source to the selected image

<li v-for="img in gallery">
  <img :src="img" @click="selected_image=img" >
</li>

Check out this Codepen example

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

v-autocomplete no selected option

Within my Vue.js 2 and Vuetify component, I am receiving the following data : [ { "anio": 2022, "__typename": "Grupo" }, { "anio": 2020, "__typename": "Grupo" }, { "anio": 2018, "__ ...

Swiper.IO pagination indicators not displaying

Why is the pagination not showing up on the image carousel I created with Swiper? Despite being in the DOM, it has a height of 0 and manual changes have no effect. Any suggestions? import Swiper from '../../vendor/swiper.min.js'; export default ...

Angularjs - Transferring the $scope object to a controller

While taking Angular's complimentary online course, I came across the following code snippet: app.controller('GalleryController', function(){ this.current = 0; this.setCurrent = function(imageNumber){ this.current = imageNumber || 0 ...

Node.js/Firebase function to delete an item from a JSON object and update the existing items

I'm currently facing a challenge with updating a JSON file in Firebase after deleting an item using the .delete() function. Here is the original JSON data before deletion: "data": [ { "position": "3", ...

Error in accessing the value from the JSON response

After uploading a photo to an external cloud CDN, I receive a JSON response containing relevant information about the uploaded photo. One key piece of data is the public_id field, which I need to store in my database. The response structure is as follows: ...

Sort object keys in a Vue component by the English representation of numbers in descending order

I've got some data for a dropdown menu. The list is currently in a random order, but I'd like to arrange it in descending order based on the key values (One, Three, Five, ...). new Vue({ el: '#app', data: { data: { Abc: ...

Which is the better choice for simply invoking a service method - subscribe or toPromise?

When implementing the search method below, I simply assign the value of BehaviourSubject in the service. However, I am unsure whether it is possible to execute this operation without using either subscribe() or toPromise() after the .pipe() block in the ...

What is the reason behind using angle brackets to access the initial value of an array with a variable inside?

I've been experimenting with this technique several times, but I still can't quite grasp why it works and haven't been able to find an answer. Can someone please explain? let myArray = [0, 1] let [myVar] = myArray console.log(myVar) // outpu ...

Difficulty with CasperJS multi-select functionality

I am currently attempting to utilize CasperJS for choosing both options in a multiple select within an HTML form: <select id="bldgs" name="bldgs" multiple="multiple" size="6" autocomplete="off"> <option value="249759290">Southeast Financia ...

What is the reason behind these sinon stubs returning undefined values?

I have created a unit test for this code snippet and used Sinon to stub the browser methods (specifically with sinon-chrome, an older but still functional library that suits my needs). /** * Returns an array of languages based on getAcceptLanguages and ge ...

Unable to play GSM extension files on a web browser due to compatibility issues

I've been attempting to play an audio file with a (.gsm) extension using <audio>, object tags, and JavaScript. <script> var myAudio = new Audio(); // creating the audio object myAudio.src = "test.gsm"; // assigning the audio file t ...

Unable to access a value from an object in Node.JS/MongoDB platform

I'm seeking assistance with my NodeJs project. The issue I am facing involves checking the seller's name and setting the newOrder.support to match the seller's support internally. Despite logging the correct value within the findOne() func ...

Add a Page to Your Domain Name using the Text Input Box

I'm looking to create an input field that allows users to enter a text string, which will be added to a domain name when submitted, redirecting the user to a specific page. Here's how the process works: The user enters 'foo' into the ...

Displaying a div when a button is clicked (PHP)

Hello everyone, I'm new to posting here so please bear with me if I seem inexperienced. On my website, there is a button that needs to disappear when clicked and be replaced by a form without refreshing the page. I was able to accomplish this using ...

What is the best way to show JSON array data in jQuery without using double quotes?

I have encountered an issue where I need to remove the double quotes from my json_encode output. To achieve this, I have used the following code: $json_string = json_encode($data); $json_string = str_replace('"','',$json_string); echo ...

What is the best way to adjust the width of a textarea based on its content

How can I dynamically set the width of a React Semantic UI textarea based on its content? Setting min-width doesn't seem to be working. Any suggestions? <Textarea key={idx} defaultValue={formattedText} className="customInpu ...

The error TS2339 is indicating that there is no property called myProperty on the type SetStateAction<User>

I'm encountering a TypeScript error while working with React that's leaving me puzzled: <html>TS2339: Property 'subEnd' does not exist on type 'SetStateAction&lt;User&gt;'.<br/>Property 'subEnd' d ...

Utilizing Vue refs to set focus on a specific element target

Clicking on "span class="before-click" should hide it, and display input class="after-click" instead. The displayed input must be in focus! However, when trying to use $refs.afterClick to access the DOM and apply .focus(), an unexpected error stati ...

What is the best way to retrieve row data from ag-grid in a Vue application?

I've integrated ag-grid into my Vue application. Within my dataset, I have three items: https://i.sstatic.net/5ymDm.png After filtering by "Toyota," only one data point appears in the grid: https://i.sstatic.net/vlmRg.png When I click on the butt ...

How can I add data to a relational table that includes a foreign key reference?

There are two tables that are related with a one to many relationship: envelopes: CREATE TABLE envelopes ( id integer DEFAULT nextval('envelope_id_seq'::regclass) PRIMARY KEY, title text NOT NULL, budget integer NOT NULL ); transact ...