vue表单数据交互提交演示教程

2020-06-12 20:51:14易采站长站整理

欢迎来到 vue-form 表单提交演示间, 你有更好的建议,请告知楼主额!

1. 客户端 html


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!-- 开发环境版本,包含了有帮助的命令行警告 -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<!-- 生产环境版本,优化了尺寸和速度 -->
<!--<script src="https://cdn.jsdelivr.net/npm/vue"></script>-->

<!-- axios -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
<h1>欢迎来到 vue-form 表单提交演示间, 你有更好的建议,请告知楼主额!</h1>
<table class="table">
<thead>
<tr>
<th>box</th>
<th>new</th>
<th>rank</th>
<th>desc</th>
<th>title</th>
</tr>
</thead>
<tbody>
<tr v-for="(v,i) in tabData">
<td>{{v.box}}</td>
<td>{{v.new}}</td>
<td>{{v.rank}}</td>
<td><input type="text" v-model="tabData[i]['desc']"></td>
<td>{{v.title}}</td>
</tr>
</tbody>
</table>
<p>
<button @click="submit" type="primary">提交</button>
</p>
</div>

<script type="application/javascript">
var app = new Vue({
el: '#app',
data: {
tabData: [
{
"box": 21650000,
"new": true,
"rank": 1,
"desc": 'desc1',
"title": "Geostorm"
},
{
"box": 13300000,
"new": true,
"rank": 2,
"desc": 'desc2',
"title": "Happy Death Day"
}
],
form: {
firstName: 'Fred',
lastName: 'Flintstone'
}
},
methods: {
submit: function () {
/**
* 多维数组对象降级为可供 axios 使用的form表单序列化数据
**/
function jsonData(arr) {
let json = "";
function fors(data, attr=false) {
data = JSON.parse(JSON.stringify(data));
for (let key in data) {
if(Array.isArray(data[key]) || Object.prototype.toString.apply(data[key]) ==='[object Object]'){
fors(data[key], true);
} else {
if(attr){
json = json + '&'+ key + '[]' +'=' + data[key];
}else {
json = json + '&'+ key +'=' + data[key];
}
}
}
}
fors(arr);
return json;
}
console.log(jsonData(this.form));