一 json-server
就是做个后台传假数据, vue测试用的
- npm -install -g json-server
- 进入到项目目录
- npm install json-server --save
- 查看package-lock.json的script
-
"json:server": "json-server --watch db.json", "json:server:remote": "json-server http://jsonplaceholder.typicode.com/db"
- 上面第一个是本地的数据, 第二个是想jsonholder的数据,前面的json:server,json:server:remote启动的名称
- 自己在package-lock同级下新建个db.json 做个数据
- 另启动个终端,npm run json:server 或者 npm run json:server:remote
二 vue-resource
先进入项目目录,
- npm install vue-resource --save
- 进入 main.js 注册
- import VueResource from 'vue-resource'
- Vue.use(VueResource)
使用方法如下
.then((data)=> 可以这样写, 又没() 无所谓
发get
methods:{
vueTest (){
this.$http.get("http://localhost:3000/users")
.then(data=>{
this.users=data.body;
},data=>{
alert("执行错误调用")
})
}
}
}
发post
methods:{
vueTest (){
this.$http.get("http://localhost:3000/users", {这是一个要发送数据的对象。像这个样子this.xx=xx})
.then(data=>{
this.users=data.body;
},data=>{
alert("执行错误调用")
})
}
}
}
三 axios 第三方的
- 进入项目目录,cnpm install axios --save
1) 不在main.js, 哪里使用哪里引用的使用方法
<script>
import Axios from 'axios'
export default {
name: "Test",
data(){
return{
users:""
}
},
methods:{
vueTest (){
Axios.get("http://localhost:3000/users")
.then(res=>{
this.users=res.data
}).catch(err=>{
alert("错误信息")
}
)
}
}
}
</script>
2)在main.js 引用
在main.js中
import axios from 'axios' Vue.prototype.$axios=axios;
使用时:this.$axios
methods:{
vueTest (){
this.$axios.get("http://localhost:3000/users")
.then(res=>{
this.users=res.data
}).catch(err=>{
alert(123)
}
)
}
}
上面发的都是get, post大概是这样
methods:{
addCustomer(e){
if (!this.customer.name || !this.customer.email || !this.customer.phone){
this.alert="xxx"
}else{
let newCustomer = {
name:this.customer.name,
phone:this.customer.phone,
email:this.customer.email,
education:this.customer.education,
graduationschool:this.customer.graduationschool,
profession:this.customer.profession,
profile:this.customer.profile
};
this.$axios.post("http://localhost:3000/users", newCustomer)
.then(res=>{
this.$router.push({path:"/", query:{msg:"信息添加成功!"}})
// 跳转
})
}
}
}
四 fetch
发get请求
methods:{
vueTest (){
fetch('http://localhost:3000/users')
.then(res=>{
return res.json()
// 返回promise对象, 并不是真正的对象
}).then(data=>{
this.users=data
// 真正的2数据
}).catch(err=>{
// 错误信息
})
}
}
发post
methods:{
vueTest (){
fetch('http://localhost:3000/users', {
method: "POST",
body:JSON.stringify(this.users),
headers:{
'Content-Type':' application/json'
// 'Content-Type': 'application/x-www-form-urlencoded'
// 发送的请求格式
}
})
.then(res=>{
return res.json()
// 返回promise对象, 并不是真正的对象, 但必须得写
}).then(data=>{
this.users=data
// 真正的2数据
}).catch(err=>{
// 错误信息
})