简单的为大家介绍一下如何在vue中使用axios
废话不多说直接上代码:
基础使用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="root">
<button @click="search">点击发送GET请求</button>
</div>
</body>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/1.5.0/axios.js"></script>
<script src="../JS/vue.js"></script>
<script>
const vm = new Vue({
el: "#root",
methods: {
search() {
// 第一种方式
// axios({
// 请求方式
// method: "GET",
// 请求的url
// url: "http://localhost:3000/posts"
// }).then(res => {
// console.log(res);
// })
// 第二种方式 常用
// 比较方便 第一个直接写url
axios.get("http://localhost:3000/posts").then(res => {
console.log(res);
})
}
},
})
</script>
</html>
渲染页面
修改页面的数组让他重新解析就能达到渲染页面的目的了
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="root">
<button @click="search">点击发送GET请求</button>
<ul>
<li v-for="item in list" :key="item.id">
{{item.id}}--{{item.title}}--{{item.author}}
</li>
</ul>
</div>
</body>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/1.5.0/axios.js"></script>
<script src="../JS/vue.js"></script>
<script>
const vm = new Vue({
el: "#root",
data: {
list: []
},
methods: {
search() {
// 第一种方式
// axios({
// 请求方式
// method: "GET",
// 请求的url
// url: "http://localhost:3000/posts"
// }).then(res => {
// console.log(res);
// })
// 第二种方式 常用
// 比较方便 第一个直接写url
axios.get("http://localhost:3000/posts").then(res => {
// console.log(res);
this.list = res.data
})
}
},
})
</script>
</html>
注:
如果碰到跨域问题怎么办
第一种:使用cors解决
第二种:在vueconfig里面配置proxy
上代码:
devServer: {
proxy: {
'/posts': {
target: 'http://localhost:3000'
}
}
},