Vue基础教程:Node.js的概述

发表时间: 2022-09-25 14:28

axios
一、axios简介

axios是独立于vue的一个项目,基于promise用于浏览器和node.js的http客户端

在浏览器中可以帮助我们完成 ajax请求的发送
在node.js中可以向远程接口发送请求
二、代码实例
1、获取数据

<script src="vue.min.js"></script>
<script src="axios.min.js"></script>
注意:测试时需要开启后端服务器,并且后端开启跨域访问权限

2、模拟后台json数据
{
"sucess":true,
"code":20000,
"message":"成功",
"data":{
"items":[
{"name":"素小暖","age":20},
{"name":"小耗子","age":30},
{"name":"凯美瑞","age":40}
]
}
}
3、html
<!DOCTYPE html>
<html lang="en">

<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">
<!--把userList数组里面数据显示 使用v-for指令 -->
<div v-for="user in userList">
{{user.name}} -- {{user.age}}
</div>
</div>
<script src="vue.min.js"></script>
<script src="axios.min.js"></script>
<script>
new Vue({
el: '#app',
//固定的结构
data: { //在data定义变量和初始值
//定义变量,值空数组
userList:[]
},
created() { //页面渲染之前执行
//调用定义的方法
this.getUserList()
},
methods:{//编写具体的方法
//创建方法 查询所有用户数据
getUserList() {
//使用axios发送ajax请求
//axios.提交方式("请求接口路径").then(箭头函数).catch(箭头函数)
axios.get("data.json")
.then(response =>{//请求成功执行then方法
//response就是请求之后返回数据
//console.log(response)
//通过response获取具体数据,赋值给定义空数组
this.userList = response.data.data.items
console.log(this.userList)
})
.catch(error =>{
}) //请求失败执行catch方法
}
}
})
</script>
</body>
</html>

想要学习更多JAVA知识的小伙伴看过来!

「链接」