How to update image source in VUE.js after form submission

I am encountering an issue with vue.js2. After submitting a form, I need to refresh the image src. When the form is submitted, a new image containing a chart is generated in the backend. The new chart image replaces the old one, but the URL remains the same. To update the image, I am using v-bind on the image src and binding it to one of the data variables. The initial image displayed before form submission is placeholder.jpg. Upon receiving a response, I call the changeChart method to update it with graph.jpg. This action successfully updates the image.

The problem arises when I modify a value and click submit again, the image does not change. However, if I first click the clear method and set chart_url back to placeholder.jpg before the next submit, the image changes correctly.

<v-img 
    v-bind:src=this.chart_url 
</v-img>


<script>
export default {
    name: "CenterComponent",
      data: function () {
        return {
            value1: "",
            value2: "",
            value3: "",
            output: null,
            chart_url: "http://127.0.0.1:5000/media/pictures/placeholder.jpg",
    }
},

methods:{
    clear(){
        this.value1 = "";
        this.value2 = "";
        this.value3 = "";
        this.output = "";
        this.chart_url = "http://127.0.0.1:5000/media/pictures/placeholder.jpg";
    },
    changeChart(){
        this.chart_url = "http://127.0.0.1:5000/media/pictures/graph.jpg"
    },
    submitForm(){
        fetch("http://127.0.0.1:5000/predict",{
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify({
                value1: this.value1,
                value2: this.value2,
                value3: this.value3
            })
        }
        ).then(response => {
            if (response.ok) {
                return response.json();
            }
        }).then(data => {
            this.output = data["prediction"];
            this.changeChart();
        });
    }
},
};
</script>

Answer №1

When you submit the form for the first time, you switch the url from 'placeholder.jpg' to 'graph.jpg'. Subsequent submissions will keep the url as 'graph.jpg', indicating that the image is cached by the browser and won't be fetched every time it changes.

To force the browser to fetch a new image, you can implement cache-busting by adding a random number at the end of the url in your changeChart function. This signals to the browser that the image needs to be retrieved again.

changeChart(){
    const randomNumber = Math.floor(Math.random() * 1000)
    this.chart_url = `http://127.0.0.1:5000/media/pictures/graph.jpg?cachebust=${randomNumber}`
},

This method appends a random number between 1-1000, but it can be customized based on your specific requirements.

Another approach is to generate a unique image name on the server during processing and return it in the POST response. This way, you avoid encountering this issue altogether.

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

What is the best way to reset an a-select component in Ant Design Vue?

I need to programmatically reset the selection in my a-select component after a specific event is triggered. Here's an example of my a-select code snippet: <a-select style="marginTop: 8px;width: 20%" @change="onChanged" > ...

Guide to Utilizing the Import Function in a Vue 3 Template

Working on a Vue 3 project, my setup includes a stuff.ts file with helpful functions that I need to utilize in my template. <script lang="ts"> import { defineComponent, onMounted } from 'vue' import { doSomething } from ' ...

Creating a route-guard in a Vue.js/Firebase authentication system for secure navigation

I have created a Vue.js/Firebase authentication interface following a tutorial. The app is mostly functioning properly, but I am experiencing issues with the route guard. Upon signing in and redirecting from "http://localhost:8080/home" to "http://localh ...

Is your Vue.js chart malfunctioning?

I have been experimenting with chart.js and vue.js. The component I created is called MessageGraph, and it is structured like this (with data extracted from the documentation): <template> <canvas id="myChart" width="400" height="400">< ...

Loop through each instance of a data record in a JSON document using Vue's v-for directive

I am currently working on a project that involves extracting data from a website that monitors traffic jams and maintenance work. My goal is to specifically retrieve information about traffic jams and display them individually. The code I am using utilize ...

In Typescript with Vue.JS, the type 'Users[]' does not include the essential properties of type 'ArrayConstructor' such as isArray, prototype, from, of, and [Symbol.species]

Embarking on my journey with typescript and vuejs, I stumbled upon a perplexing error that has halted my progress for the past 48 hours. The error message reads as: Type 'Users[]' is missing the following properties from type 'ArrayConstruct ...

Exploring the Power of Nuxt's asyncData Feature for Handling Multiple Requests

Within my application, there is a seller page showcasing products listed by the specific seller. Utilizing asyncData to retrieve all necessary data for this page has been beneficial in terms of SEO. asyncData ({params, app, error }) { return app.$axi ...

What is the process for importing a .gltf/.glb model into a Three.js application?

After browsing through several related topics on SO, I'm still unable to find a solution to my current issue. The problem I'm facing is that the .glb model simply refuses to load. My Vue application utilizes webpack (specifically the Quasar frame ...

Incorporate CSS animations prior to removing an element from an array

Before removing an item from my data table, I want to implement a CSS animation. The deletion is initiated by the @click event. I would like to preview the effect of my animation (class delete_animation) before proceeding with the actual removal. var vm ...

The function Getter is expected, but an error has occurred with "getters.doubleCounter" returning a value of 20 in VUEX

Currently, I am diving into the world of Vuex and encountering some challenges along the way. In my attempt to create a getter on my vuex instance, I am facing an error when trying to display data from one of my components: The getter should be a functi ...

Using Vue to perform multiplication on data table entries

Is there a way I can use Vue.js to multiply values in a table? The values provided are for 100g of the product. For example, if I input 200g, I would like the values to double: 318kcal, 12 fat, 48 carbs, 8 protein, and 2% iron. Similarly, inputting 50g sho ...

VueJS: using dynamic class names within the style attribute

Within my VueJS application, I have implemented Materializecss modals within single page components. Each modal requires a unique dynamic ID due to the application's requirements. The code snippet below showcases this: <template> <div :i ...

What is the optimal location for storing component fetch logic?

When should I make a REST request to retrieve data for a Vue component called Page, specifically for the properties title and content? Also, where is the best place to handle this logic? Currently, I am trying to fetch the data on the component's rea ...

Error: The options object provided for CSS Loader is not valid and does not match the API schema. Please make sure to provide the correct options when

Summary My Nuxt.js project was created using the command yarn create nuxt-app in SPA mode. However, I encountered an error after installing Storybook where running yarn dev resulted in failure to start the demo page. ERROR Failed to compile with 1 errors ...

Preventing the insertion of a line break when using Shift + Enter in Vuejs

Whenever I use a textarea to enter text, I find that I have to press Shift + Enter every time to send the text. However, upon sending, it adds /n at the end. I prefer using the Enter key for newline instead of submitting the form. Example: hello => ...

Troubleshooting why Vue.js isn't updating the DOM with two-way binding

I'm currently utilizing Vue.js for implementing two-way binding. One issue I am facing is with an edit button that should convert a text field into an input field upon clicking. However, the DOM does not update immediately as expected. For instance: ...

Utilize a for loop in Vue.js to save a fresh array of objects in a structured format

Trying to achieve the following using Vue: I have two JSON objects that provide information on languages and the number of inputs per language. Using nested loops, I display all the inputs. My goal is to create an object for each input with additional det ...

The Vue.js input for checkboxes and radios fails to toggle when both :checked and @input or @click are used simultaneously

Check out this example on JSFiddle! <script src="https://unpkg.com/vue"></script> <div id="app"> <label> <input type="checkbox" name="demo" :checked="isChecked" @input=" ...

What could be causing my Vue application to not launch after executing `npm run serve`?

These past 24 hours have been a struggle for me. I recently embarked on the journey of learning Javascript, and my choice of JS framework was Vue JS. However, when I run npm run serve, my Vue JS app bombards me with numerous errors that seem to make no se ...

What are the reasons behind the pagination with numbers not functioning properly in Vue?

I've encountered an issue with my Vue application using Vuex while implementing pagination. The problem lies in the fact that the events stored are not being displayed, and neither are the page numbers for pagination. Another issue is that the paginat ...