Vue与后端交互
vue与后端交互
Vue与后端交互有三种方式:
- jQuery的ajax,在vue中不推荐
- js自带的fetch方法
- axios,第三方
现假设向如下地址发送get请求:
http://127.0.0.1:8000/index
可以获取如下json格式数据:
{
"name":"tom",
"age":18
}
ajax
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>后端交互</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<button @click="getData">发送请求</button>
<p>name的值为:{{ name }}</p>
<p>age的值为:{{ age }}</p>
</div>
<script>
const vm = new Vue({
el: '#app',
data: {
name: '',
age: '',
},
methods: {
getData() {
$.ajax({
url: 'http://127.0.0.1:8000/index',
type: 'get',
success: res => {
this.name = res.name
this.age = res.age
}
})
}
}
})
</script>
</body>
</html>
fetch
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>后端交互</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<button @click="getData">发送请求</button>
<p>name的值为:{{ name }}</p>
<p>age的值为:{{ age }}</p>
</div>
<script>
const vm = new Vue({
el: '#app',
data: {
name: '',
age: '',
},
methods: {
getData() {
fetch('http://127.0.0.1:8000/index').then(res => res.json()).then(res => {
this.name = res.name
this.age = res.age
})
}
}
})
</script>
</body>
</html>
axios
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>后端交互</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
<button @click="getData">发送请求</button>
<p>name的值为:{{ name }}</p>
<p>age的值为:{{ age }}</p>
</div>
<script>
const vm = new Vue({
el: '#app',
data: {
name: '',
age: '',
},
methods: {
getData() {
axios.get('http://127.0.0.1:8000/index').then(res => {
console.log(res)
console.log(res.data)
this.name = res.data.name
this.age = res.data.age
})
}
}
})
</script>
</body>
</html>
可能报错问题
这可以在后端返回数据的响应头中添加键值对:
'Access-Control-Allow-Origin':'*'