【发布时间】: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 事件并执行以下操作:
<form v-on:submit.prevent="add"> -
只是在写同样的东西。您也可以简单地将您的按钮更改为
type="button"...
标签: javascript html forms vue.js