简体   繁体   English

页面使用 VueJS 不断刷新

[英]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.所以我正在尝试制作一个简单的 Web 应用程序,它从表单中获取数据并使用 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/vue@2.5.13/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?关于可能导致问题的任何想法?

This is because by default <button type="submit"/> in a <form> tag will try to submit form and reload the page这是因为默认情况下<button type="submit"/> <form>标签中的<button type="submit"/>将尝试提交表单并重新加载页面

Check detail at How do I make an HTML button not reload the page查看如何使 HTML 按钮不重新加载页面中的详细信息

If you prevent the default action on the form, it works.如果您阻止表单上的默认操作,它就会起作用。

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

I've had the same problem when working with forms in Vue and Nuxt.在 Vue 和 Nuxt 中使用表单时,我遇到了同样的问题。 Make sure that there's no errors in the terminal window where you're running your Nuxt app.确保运行 Nuxt 应用程序的终端窗口中没有错误。 Then, empty your cache in your browser and everything should work fine.然后,清空浏览器中的缓存,一切正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM