第一种自定义数据
代码语言:javascript复制//vm.js
import Vue from 'vue/dist/vue.esm';
import VueRouter from 'vue-router';
let vm = new Vue({
el:'#app',
data:{
result:0
},
//data与methods初始化时发送请求更新result
async created(){
let formdata = new FormData();//实例化FormData
formdata.append('a',34);
formdata.append('b',56);//手动添加数据
let res = await fetch('index.php',{
method:'post',
body:formdata//指定发送数据
});
this.result = await res.json();//结果转换为json,因为解析也属于异步操作所有添加await。
}
})
代码语言:javascript复制//index.php
<?php
echo $_POST['a'] $_POST['b'];
//index.html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id='app'>
{{result}}
</div>
<script type="text/javascript" src='dest/bundle.min.js'></script>
</body>
</html>
第二种发送表单数据
代码语言:javascript复制import Vue from 'vue/dist/vue.esm';
import VueRouter from 'vue-router';
let vm = new Vue({
el:'#app',
data:{
result:0
},
methods:{
async submit(){
//获取表单$refs
let form = this.$refs['form1']
let formdata = new FormData(form);
let res = await fetch(form.action,{
method:form.method,
body:formdata
});
this.result = await res.json();
}
},
template:`
//ref用于给组件内部标签取名称
<form ref='form1' @click:prevent="submit()" action='index.php' method='post' >
姓名:<input type='text' name='a' value='1'><br />
年龄:<input type='text' name='b' value='19'><br />
<input type='submit' value='提交'>
</form>
`
})