5. Vue异步操作
1 axios介绍
-
在Vue中发送异步请求,本质上还是AJAX。我们可以使用axios这个插件来简化操作!
-
使用步骤
1.引入axios核心js文件。
2.调用axios对象的方法来发起异步请求。
3.调用axios对象的方法来处理响应的数据。 -
axios常用方法
-
代码实现
- html代码
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>异步操作</title><script src="js/vue.js"></script><!--引入axios核心js文件--><script src="js/axios-0.18.0.js"></script> </head> <body> <div id="div">{{name}}<!--全称写法 v-on:click="send()" --><button @click="send()">发起请求</button> </div> </body> <script>new Vue({el:"#div",data:{name:"张三",age:18},methods:{send(){//1.发送异步请求/*说明:1.后台url的地址 "http://localhost:8080/axiosDemo01Servlet"*/axios.get("http://localhost:8080/axiosDemo01Servlet").then(resp=>{console.log(resp.data);});}}}); </script> </html>
- java代码 后续后讲解,这里不用理会
package com.itheima.sh.a_vue_axios_01;import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException;@WebServlet("/axiosDemo01Servlet") public class AxiosDemo01Servlet extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet(request, response);}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {System.out.println("hello vue");response.getWriter().print("你好vue");} }
2 案例练习
案例: 点击登录时将用户信息提交到后台,并接收后台服务器响应的好友信息显示到页面上。
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>异步请求案例</title><script src="js/vue.js"></script><script src="js/axios-0.18.0.js"></script></head>
<body><!--vue1. 视图2. 脚本data改变,视图会随之改变我们从服务器获取数据,只要修改data,视图就会改变我们无需在js中直接操作视图了
-->
<div id="div"><h1>登录页面</h1><!--v-model="user.username" :使用双向数据表绑定--><input type="text" name="username" placeholder="请输入用户名" v-model="user.username"> <br><input type="password" name="password" placeholder="请输入密码" v-model="user.password"><br><button @click="send()">登录</button><h1>主页: 显示好友列表</h1><ul><li v-for="element in list">{{element.id}},{{element.name}},{{element.age}}</li></ul>
</div></body>
<script>new Vue({el: "#div",data: {//TODO; 由于表单双向数据绑定的存在,当用户操作表单时,user就会有数据(json格式)user: {},list: []},methods: {send: function () {//1.当点击登录按钮,向后台发送请求获取好友列表,并将用户名和密码数据提交到后台/*说明:1.向后台请求地址:http://localhost:8080/axiosDemo02Servlet2.this.user就是json格式的数据:{"username":"锁哥","password":"1234"}*/axios.post("http://localhost:8080/axiosDemo02Servlet",this.user)//this.user就是json格式的数据:{"username":"锁哥","password":"1234"}.then(resp=>{//2.接收响应数据let obj = resp.data;//3.判断if(obj.flag){//查询成功//4.将后台响应的集合数据赋值给data中的listthis.list=obj.valueData;}else{//查询失败}});}}});
</script>
</html>
后台代码:(后面学习)
package com.itheima.sh.a_vue_axios_01;import com.itheima.sh.util.BaseController;import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;@WebServlet("/axiosDemo02Servlet")
public class AxiosDemo02Servlet extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet(request, response);}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {try {//1.创建集合对象保存多个好友ArrayList<Friend> list = new ArrayList<>();//2.向集合添加数据Collections.addAll(list, new Friend("001", "张三", 18), new Friend("002", "李四", 19),new Friend("003", "王五", 20));//3.将list放到Result对象中Result result = new Result(true, "查询好友成功", list);//4.将result对象转换json并响应给前端BaseController.printResult(response, result);} catch (Exception e) {e.printStackTrace();try {//6.将list放到Result对象中Result result = new Result(false, "查询好友失败");//7.将result对象转换json并响应给前端BaseController.printResult(response, result);} catch (Exception exception) {exception.printStackTrace();}}}
}
package com.itheima01.vue;import java.io.Serializable;public class Friend implements Serializable {private String id;private String name;private Integer age;public Friend() {}public Friend(String id, String name, Integer age) {this.id = id;this.name = name;this.age = age;}public String getId() {return id;}public void setId(String id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}
}
package com.itheima01.vue;import java.io.Serializable;/*javaBean的规范 (java标准实体类)1. private属性2. public 无参构造3. public get/set 方法4. 实现serializable接口 (序列化)*/
public class User implements Serializable {private String username;private String password;public User() {}public User(String username, String password) {this.username = username;this.password = password;}@Overridepublic String toString() {return "User{" +"username='" + username + '\'' +", password='" + password + '\'' +'}';}//TODO: 自己采用字符串拼接的方式输出。public String toJson() {return "{\"username\":\""+username+"\",\"password\":"+password+"}";}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}
}
package com.itheima01.vue;import java.io.Serializable;/*Result : 结果*/
public class Result implements Serializable {private boolean flag;//执行结果,true为执行成功 false为执行失败private String message;//返回结果信息private Object data;//返回数据(如果是查询成功则设置,如果是其他情况则不设置)public Result() {}//失败,或者增删改public Result(boolean flag, String message){this.flag = flag;this.message = message;}//成功的查询public Result(boolean flag, String message, Object data) {this.flag = flag;this.message = message;this.data = data;}public boolean isFlag() {return flag;}public void setFlag(boolean flag) {this.flag = flag;}public String getMessage() {return message;}public void setMessage(String message) {this.message = message;}public Object getData() {return data;}public void setData(Object data) {this.data = data;}
}
package com.itheima01.vue;import com.alibaba.fastjson.JSON;import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;public class BaseController {/*** post请求参数为json格式的数据 转换成 javaBean*/public static <T>T getBean(HttpServletRequest request,Class<T> clazz) throws IOException {ServletInputStream is = request.getInputStream();T t = JSON.parseObject(is, clazz);return t;}public static void printResult(HttpServletResponse response, Result result) throws IOException {response.setContentType("application/json;charset=utf-8");String json = JSON.toJSONString(result);response.getWriter().print(json);}
}
<dependencies><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>3.1.0</version><scope>provided</scope></dependency><!--fastjson--><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.47</version></dependency></dependencies>