What causes VueJS to automatically reload after a push array operation?

Whenever I add a value to my array using VueJS, Chrome initially displays it but then immediately reloads the webpage.

let vm = new Vue ({
    el:'#app2',

    data: {
        people: ['Robert', 'Pablo', 'Lucas', 'Teban']
    },

    methods: {
        addPerson: function() {
            this.people.push('Maxime')   
        },
    }
})

<section id="app2" style="margin-top: 100px">
    <p>{{people}}</p>
    <form>
        <button v-on:click='addPerson'>Ajouter une personne</button>
    </form>
</section>

Answer №1

Your issue arises from the fact that your <button> element is causing the form submission. When its type is not specified, it defaults to submit, triggering the form submission and refreshing the page:

submit: The button submits the form data to the server. This behavior occurs when the attribute is not defined or is set to an empty or invalid value.

To avoid this, you can do the following:

<button v-on:click='addPerson' type='button'>Add a person</button>

Alternatively, you can utilize the prevent event modifier with the click directive:

<button v-on:click.prevent='addPerson'>Add a person</button>

Another approach is to directly call event.preventDefault() within the method:

methods: {
    addPerson: function(e) {
        e.preventDefault();
        this.people.push('Maxime')   
    },
}

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

Refreshing a value in the view at regular intervals using a filter in Vue

Trying to create a countdown timer with vue, but the view is not updating. Here are my app.js and index.html: var nowDate = new Date; var nextNewYearsEve = new Date(nowDate.getFullYear(), 11, 31, 23, 59, 59, 59); var timeLeftToNewYearsEve = nextNewYears ...

Verify that the text entered in the form is accurate, and if it meets the required criteria, proceed to the next

Is it possible to achieve this without using JavaScript? If not, I'd like to find the simplest solution. I have a form that functions similar to a password entry field, and I would like to redirect users to a certain page if they type in a specific p ...

When invoking a function, a React Component utilizes the props from the first element instead of its own

Whenever I try to invoke a function of a component, it seems to be replacing the parameters and passing the props of the first array element instead of the selected one. To illustrate this issue, let's take a look at some code: Firstly, here is how ...

Ensure that the input field only accepts numerical values

Can anyone help me with an issue I'm facing in my plunker? I have an input text field that I want to accept only numbers. Despite trying normal AngularJS form validation, the event is not firing up. Has anyone encountered a similar problem or can prov ...

What is the best way to save and retrieve a JSON object as a cookie using vanilla JavaScript?

When it comes to writing the cookie, I have no issues doing it like so: ["4c3dd477c441e17957000002","4c2ac3cc68fe54616e00002e","4c3dd477c441e17957000003","4c3dd477c441e17957000004"] But what's the trick to reading the cookie? I'm currently wo ...

Pause the execution of an AJAX callback function after numerous AJAX requests

I have two separate Ajax calls in my code. Both of them have different callbacks that need to execute upon successful call. $.ajax({ type: 'POST', url: "url1", success: foo1 }); $.ajax({ type: 'POST', url: "url2", ...

AngularJS causing issues with Materializecss dropdown menu operation

I'm currently working on a web application using Materializecss and AngularJS for the front-end. However, I've encountered an issue with the dropdown menu component of Materialize not functioning as expected. Here's an example of the dropdo ...

Transforming date format from fullCalendar dayClick event to HH:MM

I'm trying to find a way to select both start and end times when clicking on a timeslot in a day using FullCalendar. For example, if I click on the 9.00am - 9.30am slot, I want to capture both times. Here's the code snippet I have so far: $(&apo ...

Scroll horizontally on a webpage using drag with JavaScript

I have been working on a unique horizontal website design that allows users to scroll horizontally by dragging the screen. I managed to successfully implement the horizontal scrolling feature, but I am facing difficulties in adding the horizontal drag-to-s ...

Delete the current code within the specified div element

Objective: The goal is to ensure that any HTML syntax code or data inside the specified <div id="feedEntries"></div> element is removed, leaving it empty. Issue: What specific syntax is required to remove all content within <div id="fe ...

Creating operations in Angular using the Model View Controller (MVC)

What is the procedure for performing an Add operation in MVC using Angular? var addProductModule = angular.module("addProductModule", []); addProductModule.factory("addProductService", ['$http', function ($http) { return { function savePro ...

Creating MySQL query results in Node.js manufacturing process

I am looking to format the MySQL result in Node.js in a specific way. The desired result format should look like this: [ { "m_idx" :1 , "contents" : { "m_name" : "a", ...

How can a static website incorporate a local image without the need for backend functionality?

I have a unique challenge with my static website. It is designed to display a local image from the user's computer without utilizing a traditional backend system. The website itself is hosted on a static file server, and all image processing must be d ...

The code splitting feature in Nuxt is currently experiencing issues

Recently, I've started working with nuxtjs and currently have 2 pages set up: -index -map The map page contains a single client-only component, while the default layout includes links to both pages. However, when I build the production version, the ...

The cachedResponse does not contain any header information

I'm currently working on figuring out the age of a cached response by utilizing the date header of the response. I attempted to do this using a plugin that utilizes cachedResponseWillBeUsed. However, when trying to access cachedResponse.headers, I am ...

A mesh from Maya that has been exported with its skin duplicated within a Three.js environment

After exporting an animated skinned mesh from Maya using the Three.js exporter, I noticed that there is always a duplicate mesh combined with it that remains static and not animated. Despite trying various export settings and ensuring that no other mesh i ...

Ways to locate the final child in a sequence

Can someone assist me in finding the last element of this chain, which is represented as an array in the code (Symptomaster history array)? I have implemented a recursive approach to solve this. Let me demonstrate it in the code snippet below. //example ...

Transform array elements into objects with associated indices and data types

Looking for assistance in restructuring this array to meet specific formatting requirements. Struggling to achieve the desired result on my own. The parent key should be named "type" and the subparent key should have a value of "category". Any suggestions ...

Using VueJS and MomentJS to calculate the passage of time

I am currently working on a website that showcases concert information. One feature I'd like to add is a progress bar for each concert event. I'm trying to figure out how to incorporate MomentJS functions into this project. This is what my ini ...

Objects being collected as arrays of arrays in garbage collection

I recently came across an article stating that a simple delete is not sufficient to release memory allocated for an object. In my current scenario, I have an Object with several subOjects structured like this: MyObject[idx]['foo']. Is there a me ...