David Mathers
David Mathers

Reputation: 165

Page keeps refreshing with VueJS

So I'm trying to make a simple web application that takes data from a form and adds them to a table using VueJS. Here is the code:

<!DOCTYPE html>
<html lang="en" xmlns:v-on="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Vue test</title>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
    <script src="app.js"></script>
</head>
<body>
<div id="vue-app">
    <form>
        <input type="text" v-model="name"/>{{name}}<br/>
        <input type="text" v-model="last"/>{{last}}<br/>
        <input type="text" v-model="index"/>{{index}}<br/>
        <select v-model="grade">
            <option>5</option>
            <option>6</option>
            <option>7</option>
            <option>8</option>
            <option>9</option>
            <option>10</option>
        </select>
        {{grade}}
        <button type="submit" v-on:click="add()">Add To Table</button>
    </form>
    <table border="1">
        <thead><td>Name</td><td>Last Name</td><td>Index</td><td>Grade</td></thead>
        <tbody>
        <tr v-for="x in arr">
            <td>{{x.first}}</td>
            <td>{{x.lastn}}</td>
            <td>{{x.index}}</td>
            <td>{{x.grade}}</td>
        </tr>
        </tbody>
    </table>
</div>
<script src="app.js"></script>
</body>
</html>

And here is the script:

new Vue ({
    el: '#vue-app',
    data: {
        name: '',
        last: '',
        index: 0,
        grade: 0,
        arr: []
    },

    methods: {
        add: function () {
            this.arr.push({first: this.name, lastn: this.last, index: this.index, grade: this.grade});
            console.log(1);
        }
    }
});

However whenever I click the submit button instead of adding the data to the table the page refreshes and nothing is added to the table.

Any ideas on what might be causing the problem?

Upvotes: 3

Views: 10096

Answers (2)

deirdreamuel
deirdreamuel

Reputation: 857

I've had the same problem when working with forms in Vue and Nuxt. Make sure that there's no errors in the terminal window where you're running your Nuxt app. Then, empty your cache in your browser and everything should work fine.

Upvotes: 0

yue you
yue you

Reputation: 2264

This is because by default <button type="submit"/> in a <form> tag will try to submit form and reload the page

Check detail at How do I make an HTML button not reload the page

If you prevent the default action on the form, it works.

<form @submit.prevent="add()">

Upvotes: 8

Related Questions