【问题标题】:Page keeps refreshing with VueJS页面使用 VueJS 不断刷新
【发布时间】:2018-07-14 16:03:00
【问题描述】:

所以我正在尝试制作一个简单的 Web 应用程序,它从表单中获取数据并使用 VueJS 将它们添加到表中。这是代码:

<!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>

这是脚本:

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);
        }
    }
});

但是,每当我单击提交按钮而不是将数据添加到表中时,页面都会刷新,并且没有任何内容添加到表中。

关于可能导致问题的任何想法?

【问题讨论】:

  • 好吧,您实际上是在提交表单(到相同的 URL)。您可能想尝试prevent this default 的行为。 View a Vue example here.
  • 为了防止页面刷新,你必须阻止它提交。不要在提交按钮中调用 add() 函数,而是从提交按钮中删除整个 v-on 事件并执行以下操作:&lt;form v-on:submit.prevent="add"&gt;
  • 只是在写同样的东西。您也可以简单地将您的按钮更改为type="button"...

标签: javascript html forms vue.js


【解决方案1】:

这是因为默认情况下,&lt;form&gt; 标签中的&lt;button type="submit"/&gt; 会尝试提交表单并重新加载页面

How do I make an HTML button not reload the page查看详情

如果您阻止表单上的默认操作,它会起作用。

&lt;form @submit.prevent="add()"&gt;

【讨论】:

  • 实际上,您最好在&lt;form&gt; 上执行@submit.prevent="submitFunc"。这样您就不会移动表单的功能
【解决方案2】:

我在 Vue 和 Nuxt 中使用表单时遇到了同样的问题。确保运行 Nuxt 应用程序的终端窗口中没有错误。然后,清空浏览器中的缓存,一切正常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-08
    • 1970-01-01
    • 2019-10-14
    • 2019-02-01
    • 2013-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多