vue----Fetch/Axios
Axios、fetch:前端通信框架;因为 Vue 的边界很明确,就是为了处理 DOM,所以并不具备通信能力,此时就需要额外使用一个通信框架与服务器交互;当然也可以直接选择使用 jQuery 提供的 AJAX 通信功能;
Fetch
get请求
<template>
<div>
home
</div>
</template>
<script lang="ts">
import {Component,Vue} from "vue-property-decorator"
@Component({
components:{},
mounted(){
const result = fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => {return response.json()}) //可以简写 .then(response => response.json())
.then(json => console.log(json)) //json等于return response.json()
}
})
export default class Home extends Vue{
}
</script>
<style scoped>
</style>
post请求(模拟form表单提交数据)
<template>
<div>
<form @submit.prevent="onsubmit">
<input v-model="userinfo.username"></input>
<button type="submit">提交</button>
</form>
</div>
</template>
<script lang="ts">
import {Component,Vue} from "vue-property-decorator"
@Component({
components:{},
data(){
return{
userinfo:{
username:''
}
}
},
methods:{
onsubmit(){
fetch("https://jsonplaceholder.typicode.com/todos",{
method:"POST",
body:JSON.stringify(this.$data.userinfo),
}).then(res=>{
console.log(res)
})
}
}
})
export default class Home extends Vue{
}
</script>
<style scoped>
</style>
Axios
Axios 是一个开源的可以用在浏览器端和 NodeJS 的异步通信框架,她的主要作用就是实现 AJAX 异步通信,其功能特点如下:
- 从浏览器中创建
XMLHttpRequests - 从
node.js创建http请求 - 支持
Promise API - 拦截请求和响应
- 转换请求数据和响应数据
- 取消请求
- 自动转换
JSON数据 - 客户端支持防御
XSRF(跨站请求伪造)
GitHub:https://github.com/axios/axios
安装
npm install axios
调用 get 请求
调用 axios 的 get 请求并自动装箱数据
axios
.get('data.json')
.then(response => (this.info = response.data));
完整的 HTML
关于promise:https://blog.csdn.net/hyupeng1006/article/details/80351174
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>网络篇 Axios</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="vue">
<div>名称:{{info.name}}</div>
<div>地址:{{info.address.country}}-{{info.address.city}}-{{info.address.street}}</div>
<div>链接:<a v-bind:href="info.url" target="_blank">{{info.url}}</a> </div>
</div>
<script type="text/javascript">
var vm = new Vue({
el: '#vue',
data() {
return {
info: {
name: null,
address: {
country: null,
city: null,
street: null
},
url: null
}
}
},
mounted() {
axios
.get('data.json')
.then(response => (this.info = response.data));
}
});
</script>
</body>
</html>

浙公网安备 33010602011771号