Ajax&Vue
1、Ajax
1.1、概述
- AJAX(Asynchronous JavaScript And XML):異步的JavaScript和XML
- 作用
- 1.與服務器進行資料交換:通過ajax可以給服務器發送請求,服務器將資料直接回應回給瀏覽器,
- 如圖是沒使用Ajax的時候,各個請求之間的流程

- Servlet呼叫完業務邏輯層后將資料存盤到域物件中,然后跳轉到指定的JSP頁面,在頁面上使用EL運算式和JSTL標簽庫進行資料的展示
- 在學習Ajax后,就可以使用Ajax和服務器進行通信,以達到使用HTML+Ajax來替代JSP頁面,

- 在上圖中,瀏覽器發送請求給Servlet,Servlet呼叫完業務邏輯層后將資料直接回應回給瀏覽器頁面,頁面使用HTML來進行資料展示
- 如圖是沒使用Ajax的時候,各個請求之間的流程
- 2.進行異步互動:可以在不重新加載整個頁面的情況下(區域重繪),與服務器交換資料并更新部分網頁的技術,如:搜索聯想、用戶名是否可用校驗,等等
- 1.與服務器進行資料交換:通過ajax可以給服務器發送請求,服務器將資料直接回應回給瀏覽器,
1.2、同步和異步的概念
- 同步發送請求的程序如下所示

- 瀏覽器頁面發送請求給服務器,在服務器處理請求的程序中,瀏覽器頁面不能做其他操作,只能等到服務器回應結束之后,瀏覽器頁面才能繼續其他操作
- 異步發送請求的程序如下所示

- 瀏覽器頁面發送請求給服務器,在服務器處理請求的程序中,瀏覽器頁面還可以做其他的操作
1.3、Ajax入門
1.3.1、客戶端代碼
-
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <input><br> <input type="button" value="https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/點我,我在睡覺" onclick="sendAjax()"> </body> <script> function sendAjax() { //1.創建核心物件 xmlhttp=null; if (window.XMLHttpRequest) {// code for IE7, Firefox, Opera, etc. xmlhttp=new XMLHttpRequest(); } else if (window.ActiveXObject) {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } //2.明確發送的請求方式和請求路徑 xmlhttp.open("get","/day28/ajaxServlet?username=tom") //3.發送請求 xmlhttp.send() //4.處理回應 xmlhttp.onreadystatechange=function () { //當回應完成的時候且回應正常完成的時候 if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { alert(xmlhttp.responseText); } } } </script> </html>
1.3.2、服務端代碼
-
package com.itheima.web.servlet; 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(value = "https://www.cnblogs.com/ajaxServlet") public class AjaxServlet 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 { //獲取發送過來的引數 String username = request.getParameter("username"); System.out.println(username); //生成回應 response.getWriter().print("ok~~~"); } }
1.3.3、實作效果

- 不難發現,點擊按鈕后,整個頁面并沒有發生跳轉,只是進行了區域的重繪
1.4、校驗用戶名是否存在案例(僅測驗,不做過多的邏輯判斷)
1.4.1、需求
- 在完成用戶注冊的時候,當用戶名輸入框失去焦點時,校驗用戶名是否在資料庫中存在
1.4.2、分析
- 前端完成的邏輯
- 1.給用戶名輸入框系結游標失去焦點事件
onblur - 2.發送ajax請求,攜帶username引數
- 3.處理回應:是否顯示提示資訊
- 1.給用戶名輸入框系結游標失去焦點事件
- 后端完成的邏輯
- 1.接收用戶名
- 2.呼叫service查詢User
- 3.回傳標記
1.4.3、整體流程圖
1.4.4、前端實作
-
Step1:給用戶名輸入框系結游標失去焦點事件
-
//1. 給用戶名輸入框系結 失去焦點事件 document.getElementById("username").onblur = function () { }
-
-
Step2:發送ajax請求,攜帶username引數
-
//2. 發送ajax請求 //2.1. 創建核心物件 var xhttp; if (window.XMLHttpRequest) { xhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xhttp = new ActiveXObject("Microsoft.XMLHTTP"); } //2.2. 發送請求 xhttp.open("GET", "http://localhost:8080/ajax-demo/selectUserServlet); xhttp.send(); //2.3. 獲取回應 xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { //處理回應的結果 } }; -
由于我們發送的是 GET 請求,所以需要在 URL 后拼接從輸入框獲取的用戶名資料,而我們在
第一步系結的匿名函式中通過以下代碼可以獲取用戶名資料 -
// 獲取用戶名的值 var username = this.value; //this : 給誰系結的事件,this就代表誰 -
而攜帶資料需要將 URL 修改為:
-
xhttp.open("GET", "http://localhost:8080/ajax-demo/selectUserServlet?username="+username);
-
-
Step3:處理回應,根據回應判斷是否顯示提示資訊
-
當
this.readyState == 4 && this.status == 200條件滿足時,說明已經成功回應資料了 -
此時需要判斷回應的資料是否是 "true" 字串,如果是說明用戶名已經占用給出錯誤提示;如果不是說明用戶名未被占用清除錯誤提示,代碼如下
-
//判斷 if(this.responseText == "true"){ //用戶名存在,顯示提示資訊 document.getElementById("username_err").style.display = ''; }else { //用戶名不存在 ,清楚提示資訊 document.getElementById("username_err").style.display = 'none'; }
-
-
-
完整JS代碼
-
//1. 給用戶名輸入框系結 失去焦點事件 document.getElementById("username").onblur = function () { //2. 發送ajax請求 // 獲取用戶名的值 var username = this.value; //2.1. 創建核心物件 var xhttp; if (window.XMLHttpRequest) { xhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xhttp = new ActiveXObject("Microsoft.XMLHTTP"); } //2.2. 發送請求 xhttp.open("GET", "http://localhost:8080/ajax-demo/selectUserServlet?username="+username); xhttp.send(); //2.3. 獲取回應 xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { //alert(this.responseText); //判斷 if(this.responseText == "true"){ //用戶名存在,顯示提示資訊 document.getElementById("username_err").style.display = ''; }else { //用戶名不存在 ,清楚提示資訊 document.getElementById("username_err").style.display = 'none'; } } }; }
-
1.4.5、后端實作
-
@WebServlet("/selectUserServlet") public class SelectUserServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1. 接收用戶名 String username = request.getParameter("username"); //2. 呼叫service查詢User物件,此處不進行業務邏輯處理,直接給 flag 賦值為 true,表明用戶名占用 boolean flag = true; //3. 回應標記 response.getWriter().write("" + flag); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
1.4.6、實作效果
2、Axios
- 概念
- Axios是對原生的Ajax進行封裝,簡化書寫
2.1、基本使用
-
1.引入axios的js檔案
-
<script src="https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/js/axios-0.18.0.js"></script>
-
-
2.使用axios發送ajax請求
-
發送get請求
-
axios({ method:"get", url:"http://localhost:8080/ajax-demo1/aJAXDemo1?username=zhangsan" }).then(function (resp){ alert(resp.data); });
-
-
發送post請求
-
axios({ method:"post", url:"http://localhost:8080/ajax-demo1/aJAXDemo1", data:"username=zhangsan" }).then(function (resp){ alert(resp.data); });
-
-
-
說明
axios()是用來發送異步請求的,小括號中使用js物件傳遞相關的引數method屬性:用來設定請求方式的,取值為get或者posturl屬性:用來書寫請求的資源路徑,如果是get請求,需要將請求引數拼接到路徑的后面,格式為:url?引數名1=引數值1&引數名2=引數值2data屬性:作為請求體被發送的資料,也就是說如果是post請求的話,資料需要作為data屬性的值
then()需要傳遞一個匿名函式,then()中傳遞的匿名函式稱為回呼函式,意思是該匿名函式在發送請求的時候不會被呼叫,而是在成功回應后呼叫的函式,resp屬性是對回應的資料進行封裝的物件,通過resp.data可以獲取到回應的資料
2.2、基本使用
2.2.1、后端實作
-
@WebServlet("/axiosServlet") public class AxiosServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("get..."); //1. 接收請求引數 String username = request.getParameter("username"); System.out.println(username); //2. 回應資料 response.getWriter().write("hello Axios~"); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("post..."); this.doGet(request, response); } }
2.2.2、前端實作
-
1.引入js檔案
-
<script src="https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/js/axios-0.18.0.js"></script>
-
-
2.發送ajax請求
-
get請求
-
axios({ method:"get", url:"http://localhost:8080/ajax-demo/axiosServlet?username=zhangsan" }).then(function (resp) { alert(resp.data); })
-
-
post請求
-
axios({ method:"post", url:"http://localhost:8080/ajax-demo/axiosServlet", data:"username=zhangsan" }).then(function (resp) { alert(resp.data); })
-
-
-
完整代碼
-
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>axios-demo</title> </head> <body> <input type="button" value="https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/發送get請求" id="btn1"> <input type="button" value="https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/發送post請求" id="btn2"> </body> <!--匯入axios.js--> <script src="https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/js/axios-0.18.0.js"></script> <!--撰寫axios的代碼--> <script> document.getElementById("btn1").onclick = function () { // axios({ // method: "get", // url: "axiosServlet?username=tom" // }).then(function (response) { // // console.log(response); // // console.log(response.data); // window.alert(response); // window.alert(response.data); // }); // axios更簡化的寫法 axios.get("axiosServlet?username=tom").then(response => { console.log(response.data); }); } document.getElementById("btn2").onclick = function () { // axios({ // method: "post", // url: "axiosServlet", // data: "username=tom" // }).then(function (response) { // // console.log(response); // // console.log(response.data); // window.alert(response); // window.alert(response.data); // }); // axios更簡化的寫法 axios.post("axiosServlet", "username=tom").then(response => { console.log(response.data); }); } </script> </html>
-
2.2.3、實作效果
2.3、Axios請求方法別名
get請求 :axios.get(url[,config])delete請求 :axios.delete(url[,config])head請求 :axios.head(url[,config])options請求 :axios.option(url[,config])post請求:axios.post(url[,data[,config])put請求:axios.put(url[,data[,config])patch請求:axios.patch(url[,data[,config])
PS:
axios會自動對JSON串進行轉換- 發送異步請求時,如果請求引數是
JSON格式,那請求方式必須是POST,因為JSON串需要放在請求體中
2.4、使用Axios和JSON完成學生串列資料查詢
雖然實作的效果差不多,但是實際上免去了JSTL中復雜的撰寫格式
2.4.1、前端實作
-
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>學生資訊</title> </head> <body> <hr> <table id="studentTable" border="1" cellspacing="0" align="center"> </table> <script src="https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/js/axios-0.18.0.js"></script> <!--<script>window.alert("等待頁面加載.....");</script>--> <script> // 在頁面加載完成的時候,展示資料 console.log("等待頁面加載....."); window.alert("等待頁面加載....."); window.onload = function () { window.alert("頁面加載成功,正在發送ajax請求!"); // 發送ajax的get請求,獲取所有學生的資訊 axios.get("selectAllStudentsServlet").then(response => { // console.log(response.data); // 定義表格中的首行資訊 let startTr = "<tr>\n" + " <th>序號</th>\n" + " <th>學號</th>\n" + " <th>姓名</th>\n" + " <th>年齡</th>\n" + " <th>性別</th>\n" + " <th>語文成績</th>\n" + " <th>數學成績</th>\n" + " <th>英語成績</th>\n" + " <th>操作</th>\n" + " </tr>"; // 定義表格中的末尾資訊 let endTr = "<tr align=\"center\">\n" + " <td></td>\n" + " <td></td>\n" + " <td></td>\n" + " <td></td>\n" + " <td></td>\n" + " <td></td>\n" + " <td></td>\n" + " <td></td>\n" + " <td><input type=\"button\" value=https://www.cnblogs.com/"新增學生資訊\" onclick=\"location.href=https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/('#')\"></td>\n" + " </tr>"; let middleTr = ""; // 遍歷json陣列,獲取每個學生物件 // 獲取回傳的json陣列 let arr = response.data; for (let i = 0; i < arr.length; i++) { // 將每個品牌封裝成tr標簽 middleTr += "<tr align=\"center\">\n" + " <td>" + (i + 1) + "</td>\n" + " <td>" + (arr[i].stuNumber) + "</td>\n" + " <td>" + (arr[i].name) + "</td>\n" + " <td>" + (arr[i].age) + "</td>\n" + " <td>" + (arr[i].sex) + "</td>\n" + " <td>" + (arr[i].chineseScore) + "</td>\n" + " <td>" + (arr[i].mathScore) + "</td>\n" + " <td>" + (arr[i].englishScore) + "</td>\n" + " <td>\n" + " <input type=\"button\" src=https://www.cnblogs.com/"#\" value=https://www.cnblogs.com/"修改\">\n" + " <input type=\"button\" src=https://www.cnblogs.com/"#\" value=https://www.cnblogs.com/"洗掉\">\n" + " </td>\n" + " </tr>"; } // 將所有的tr標簽放入table標簽終 document.getElementById("studentTable").innerHTML = startTr + middleTr + endTr; window.alert(document.getElementById("studentTable").innerHTML); }); } </script> </body> </html>
2.4.2、后端實作
-
package com.coolman.web.servlet; import com.alibaba.fastjson.JSON; import com.coolman.pojo.Student; import com.coolman.service.StudentService; 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.List; @WebServlet("/selectAllStudentsServlet") public class SelectAllStudentsServlet 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 { // 在這里處理請求 // 呼叫服務,查詢所有學生資訊 List<Student> students = new StudentService().selectAllStudent(); // 將List物件轉換成JSON格式的字串 String str = JSON.toJSONString(students); // 處理中文亂碼問題 // 方案1 // response.setContentType("text/html;charset=utf-8"); // 方案2 response.setContentType("application/json;charset=utf-8"); // 回傳字串 response.getWriter().print(str); } }
2.5、使用Axios和JSON完成新增學生資訊
2.5.1、前端實作
-
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>添加學生資訊</title> </head> <body> <h3 align="center" style="color: red">添加學生資訊</h3> <form> <div align="center"> <span>學號: <input name="stuNumber" id="stuNumber"> <br/> <span style="color: red" id="stuNumber_err_msg"></span> <br/> </span> <span>姓名: <input name="name" id="name"> <br> <span style="color: red" id="name_err_msg"></span> <br> </span> <span>年齡: <input name="age" id="age"> <br> <span style="color: red" id="age_err_msg"></span> <br> </span> <span>性別: <input name="sex" id="sex"> <br> <span style="color: red" id="sex_err_msg"></span> <br> </span> <span>語文成績: <input name="chineseScore" id="chineseScore"> <br> <span style="color: red" id="chineseScore_err_msg"></span> <br> </span> <span>數學成績: <input name="mathScore" id="mathScore"> <br> <span style="color: red" id="mathScore_err_msg"></span> <br> </span> <span>英語成績: <input name="englishScore" id="englishScore"> <br> <span style="color: red" id="englishScore_err_msg"></span> <br> </span> <input id="commit" type="button" value="https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/提交"> </div> </form> <script src="https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/js/axios-0.18.0.js"></script> <script> // 定義一個物件,接收輸入框中的資訊 let studentFormData = https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/{ stuNumber:"", name: "", age: "", sex: "", chineseScore: "", mathScore: "", englishScore: "", } // 判斷輸入框是否為空 document.getElementById("stuNumber").onblur = function () { let stuNumber = this.value; if (stuNumber != "") { studentFormData.stuNumber = stuNumber; } else { document.getElementById("stuNumber_err_msg").innerText = "學號不能為空"; } }; document.getElementById("name").onblur = function () { let name = this.value; if (name != "") { studentFormData.name = name; } else { document.getElementById("name_err_msg").innerText = "姓名不能為空"; } }; document.getElementById("age").onblur = function () { let age = this.value; if (age != "") { studentFormData.age = age; } else { document.getElementById("age_err_msg").innerText = "年齡不能為空"; } }; document.getElementById("sex").onblur = function () { let sex = this.value; if (sex != "") { studentFormData.sex = sex; } else { document.getElementById("sex_err_msg").innerText = "性別不能為空"; } }; document.getElementById("chineseScore").onblur = function () { let chineseScore = this.value; if (chineseScore != "") { studentFormData.chineseScore = chineseScore; } else { document.getElementById("chineseScore_err_msg").innerText = "語文成績不能為空"; } }; document.getElementById("mathScore").onblur = function () { let mathScore = this.value; if (mathScore != "") { studentFormData.mathScore = mathScore; } else { document.getElementById("mathScore_err_msg").innerText = "數學成績不能為空"; } }; document.getElementById("englishScore").onblur = function () { let englishScore = this.value; if (englishScore != "") { studentFormData.englishScore = englishScore; } else { document.getElementById("englishScore_err_msg").innerText = "英語成績不能為空"; } }; // 系結提交事件 document.getElementById("commit").onclick = function () { // 判斷物件是否存在資料 // 不存在則不發送添加學生資訊的請求 if (studentFormData.name != "" && studentFormData.age != "" && studentFormData.sex != "" && studentFormData.stuNumber != "" && studentFormData.chineseScore != "" && studentFormData.mathScore != "" && studentFormData.englishScore != "" ) { // 發送ajax請求,添加學生資料 axios.post("addStudentServlet", studentFormData).then(response => { if (response.data =https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/="ok") { location.href = "https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/studentList.html"; } }); } else { window.alert("請補全資訊!"); } } </script> </body> </html>
2.5.2、后端實作
-
package com.coolman.web.servlet; import com.alibaba.fastjson.JSON; import com.coolman.pojo.Student; import com.coolman.service.StudentService; import javax.servlet.ServletException; import javax.servlet.ServletInputStream; 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("/addStudentServlet") public class AddStudentServlet 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 { // 在這里處理請求 //1.獲取請求體中的流 ServletInputStream is = request.getInputStream(); //2.把流轉成java物件 Student student = JSON.parseObject(is, Student.class); //3.呼叫service中保存方法 new StudentService().addStudent(student); //4.通知前端保存成功 response.getWriter().print("ok"); } }
3、Vue
3.1、概念
- Vue是一套前端框架,免除原生JavaScript中的DOM操作,簡化書寫,其基于MVVM(Model-View-ViewModel)思想,實作資料的雙向系結,將編程的關注點放在資料上,
- MVC思想圖解

- MVC:只能實作模型到視圖的單向展示,無法實作雙向系結,
- 雙向系結的概念
- 指的是當資料模型的資料發生變化的時候,頁面展示也會隨之發生變化,而如果表單資料發生變化,系結的模型資料也隨之發生變化,
- MVVM思想圖解

- 圖中的Model就是我們的資料,View是視圖,也就是頁面標簽,用戶可以通過瀏覽器看到的內容
- Model和View是通過ViewModel物件進行雙向系結的,而ViewModel物件是Vue提供的
- MVVM簡單示例
- 輸入框系結username模型資料,頁面上使用
{{}}系結username模型資料 - 通過瀏覽器打開該頁面可以看到如下頁面
- 當我們在輸入框中輸入內容的同時,輸入框后面也隨之實時的展示我們輸入的內容,這就是雙向系結的效果
- 輸入框系結username模型資料,頁面上使用
3.2、Vue入門
-
Vue使用起來比較簡單,可以分為如下三步
-
1.新建HTML頁面,引入Vue.js檔案
-
<script src="https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/js/vue.js"></script>
-
-
2.在js代碼區域,創建Vue核心物件,進行資料系結
-
new Vue({ el: "#app", data() { return { username: "" } } }); -
創建Vue物件的時候,需要傳遞一個js物件,而該物件中需要如下屬性:
el:用來指定哪些標簽受Vue管理,該屬性取值#app中的app需要的是受管理的標簽的id屬性值data:用來定義資料模型methods:用來定義函式
-
-
3.撰寫視圖
-
<div id="app"> <input name="username" v-model="username" > {{username}} </div> -
{{}}是Vue中定義的插值運算式,在里面寫資料模型,到時候會將該模型的資料值展示在這個位置
-
-
-
整體代碼如下
-
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="app"> <input v-model="username"> <!--插值運算式--> {{username}} </div> <script src="https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/js/vue.js"></script> <script> //1. 創建Vue核心物件 new Vue({ el:"#app", data(){ // data() 是 ECMAScript 6 版本的新的寫法 return { username:"" } } /*data: function () { return { username:"" } }*/ }); </script> </body> </html>
-
3.3、Vue指令
-
指令:HTML標簽上帶有v-前綴的特殊屬性,不同指令具有不同含義,例如:v-if,v-for....
-
常用的指令如下所示
-
指令 作用 v-bind 為HTML標簽系結屬性值,如設定href,css樣式等等 v-model 在表單元素上創建雙向資料系結 v-on 為HTML標簽系結事件 v-if 條件性的渲染某元素,判定為true的時候渲染,否則不渲染 v-else 同if-else v-else-if 同if-else if-else v-show 根據條件展示某元素,區別在于切換的是display屬性的值 v-for 串列渲染,遍歷容器的元素或者物件的屬性
-
3.3.1、v-bind示例
-
<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:v-bind="http://www.w3.org/1999/xhtml"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="app"> <!-- v-bind 該指令可以給標簽原有屬性系結模型資料 v-bind 可以簡化寫成 : --> <a v-bind:href="https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/url">點我一下</a><br/> <a :href="https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/url">點我一下</a><br/> </div> </body> <!--匯入vue.js--> <script src="https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/js/vue.js"></script> <!--定義vue物件--> <script> new Vue({ el: "#app", data: { url: "https://www.baidu.com" } }) </script> </html>- 通過瀏覽器打開該頁面,可以發現,鏈接標簽就系結了data中的url資料模型
3.3.2、v-model示例
-
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="app"> <a :href="https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/url">點我一下</a><br/> <!-- v-model 指令可以給表單項標簽系結模型資料,這樣就能實作雙向系結效果 --> <input v-model="url"/> </div> </body> <!--匯入vue.js--> <script src="https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/js/vue.js"></script> <!--定義vue物件--> <script> new Vue({ el:"#app", data:{ url:"https://www.bing.com" } }); </script> </html>- 通過瀏覽器打開該頁面,發現a標簽的href屬性會隨著輸入框輸入的路徑變化而變化,這是因為超鏈接和輸入框系結的是同一個資料模型
3.3.3、v-on示例
-
<!DOCTYPE html> <html lang="en" xmlns:v-on="http://www.w3.org/1999/xhtml"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="app"> <!-- v-on 指令用于系結事件,具體方法邏輯需要在vue的methods屬性中體現 v-on 可以簡寫為 @ --> <input type="button" value="https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/點我44" v-on:click="show1()"/> <input type="button" value="https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/點我44" v-on:click="show2"/> <input type="button" value="https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/點我44" @click="show3()"/> </div> </body> <!--匯入vue.js--> <script src="https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/js/vue.js"></script> <!--定義vue物件--> <script> new Vue({ el:"#app", data:{ }, methods: { show1() { alert("我被點了,嚶嚶嚶"); }, show2() { alert("我又被點了,嚶嚶嚶"); }, show3() { alert("我又又被點了,嚶嚶嚶"); } } }); </script> </html>- v-on:后面的事件名稱是之前原生事件屬性名去掉on
- 例如
- 單擊事件:事件屬性名是onclick,而在vue中使用的是:v-on:onclick
- 失去焦點事件:事件屬性名是onblur,而在vue中使用的是:v-on:blur
3.3.4、v-if示例
-
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="app"> <!-- 語法: v-if="布爾運算式" v-else-if="布爾運算式" v-else 注意: 當得到結果為true時,所在的元素才會被渲染 v-else-if或v-else元素必須跟在v-if的元素的后面,否則它將不會被識別 --> <!--從文本框輸入成績, 然后判斷成績是否及格 >=60:及格 <60:不及格 其他數字:超出范圍 非數字:資料非法--> <h3>考試成績練習</h3> 請輸入成績:<input type="text" v-model="score"><br> 你本次考試成績: <div v-if="score == ''"></div> <div v-else-if="score > 100 || score < 0">超出范圍</div> <div v-else-if="score >= 60">及格</div> <div v-else-if="score < 60">不及格</div> <div v-else>資料非法</div> <hr> <div v-show="score==100">滿分</div> </div> </body> <!--匯入vue.js--> <script src="https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/js/vue.js"></script> <!--定義vue物件--> <script> new Vue({ el:"#app", data:{ score:"", }, }); </script> </html>
3.3.5、v-for示例
-
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="app"> <!-- 語法: <標簽 v-for="(變數名,索引) in 集合模型資料"> {{變數名}} </標簽> 注意: 遍歷那個標簽就把v-for寫在那個標簽中 不需要索引時可以不寫,這時候小括號也可以省略 --> <ul> <li v-for="city in cities">{{city}}</li> </ul> <hr/> <ul> <li v-for="(city, index) in cities"> {{index + 1}} : {{city}} </li> </ul> </div> </body> <!--匯入vue.js--> <script src="https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/js/vue.js"></script> <!--定義vue物件--> <script> new Vue({ el:"#app", data:{ cities:["北京", "上海", "廣州", "深圳"] } }); </script> </html>
3.3.6、生命周期
-
宣告周期的八個階段,每觸發一個生命周期事件,會自動執行一個生命周期方法,這些生命周期方法也被稱為鉤子方法
-
狀態 階段周期 beforeCreate 創建前 created 創建后 beforeMount 載入前 mounted 掛載完成 beforeUpdate 更新前 updated 更新后 beforeDestory 銷毀前 destoryed 銷毀后
-
-
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="app"> <!-- --> </div> </body> <!--匯入vue.js--> <script src="https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/js/vue.js"></script> <!--定義vue物件--> <script> new Vue({ el:"#app", mounted() { console.log("I am mounted method"); }, created() { console.log("I am create method"); } }); </script> </html>
3.4、使用Vue簡化基于ajax做的查詢所有和添加功能
3.4.1、學生串列資訊頁面
-
前端實作
-
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>學生資訊</title> </head> <body> <hr> <table id="studentTable" border="1" cellspacing="0" align="center"> <tr> <th>序號</th> <th>學號</th> <th>姓名</th> <th>年齡</th> <th>性別</th> <th>語文成績</th> <th>數學成績</th> <th>英語成績</th> <th>操作</th> </tr> <tr align="center" v-for="(student, index) in students"> <td>{{index + 1}}</td> <td>{{student.stuNumber}}</td> <td>{{student.name}}</td> <td>{{student.age}}</td> <td>{{student.sex}}</td> <td>{{student.chineseScore}}</td> <td>{{student.mathScore}}</td> <td>{{student.englishScore}}</td> <td><a href="https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/#">修改</a> <a href="https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/#">洗掉</a></td> </tr> <tr align="center"> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td><input type="button" value="https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/新增學生資訊" onclick="location.href=https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/('addStudent.html')"></td> </tr> </table> <script src="https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/js/axios-0.18.0.js"></script> <!--匯入vue.js--> <script src="https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/js/vue.js"></script> <script> new Vue({ el: "#studentTable", data: { students: [] }, created(){ axios.get("selectAllStudentsServlet").then(response => { this.students = response.data; }) } }); </script> </body> </html>
-
-
后端實作
-
package com.coolman.web.servlet; import com.alibaba.fastjson.JSON; import com.coolman.pojo.Student; import com.coolman.service.StudentService; 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.List; @WebServlet("/selectAllStudentsServlet") public class SelectAllStudentsServlet 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 { // 在這里處理請求 // 呼叫服務,查詢所有學生資訊 List<Student> students = new StudentService().selectAllStudent(); // 將List物件轉換成JSON格式的字串 String str = JSON.toJSONString(students); // 處理中文亂碼問題 // 方案1 // response.setContentType("text/html;charset=utf-8"); // 方案2 response.setContentType("application/json;charset=utf-8"); // 回傳字串 response.getWriter().print(str); } }
-
3.4.2、添加學生資訊
-
前端實作
-
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>添加學生資訊</title> </head> <body> <h3 align="center" style="color: red">添加學生資訊</h3> <form> <div align="center" id="addStudent"> <span>學號: <input name="stuNumber" id="stuNumber" v-model="student.stuNumber"> <br/> <span style="color: red" id="stuNumber_err_msg"></span> <br/> </span> <span>姓名: <input name="name" id="name" v-model="student.name"> <br> <span style="color: red" id="name_err_msg"></span> <br> </span> <span>年齡: <input name="age" id="age" v-model="student.age"> <br> <span style="color: red" id="age_err_msg"></span> <br> </span> <span>性別: <input name="sex" id="sex" v-model="student.sex"> <br> <span style="color: red" id="sex_err_msg"></span> <br> </span> <span>語文成績: <input name="chineseScore" id="chineseScore" v-model="student.chineseScore"> <br> <span style="color: red" id="chineseScore_err_msg"></span> <br> </span> <span>數學成績: <input name="mathScore" id="mathScore" v-model="student.mathScore"> <br> <span style="color: red" id="mathScore_err_msg"></span> <br> </span> <span>英語成績: <input name="englishScore" id="englishScore" v-model="student.englishScore"> <br> <span style="color: red" id="englishScore_err_msg"></span> <br> </span> <input id="commit" type="button" value="https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/提交" v-on:click="add()"> </div> </form> <script src="https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/js/axios-0.18.0.js"></script> <script src="https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/js/vue.js"></script> <script> new Vue({ el: "#addStudent", data: { student: { stuNumber: "", name: "", age: "", sex: "", chineseScore: "", mathScore: "", englishScore: "", } }, methods: { add() { axios.post("addStudentServlet", this.student).then(response =>{ if (response.data =https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/="ok") { window.location.href = "https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/studentList.html"; } }) } } }) </script> </body> </html>
-
-
后端實作
-
package com.coolman.web.servlet; import com.alibaba.fastjson.JSON; import com.coolman.pojo.Student; import com.coolman.service.StudentService; import javax.servlet.ServletException; import javax.servlet.ServletInputStream; 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("/addStudentServlet") public class AddStudentServlet 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 { // 在這里處理請求 //1.獲取請求體中的流 ServletInputStream is = request.getInputStream(); //2.把流轉成java物件 Student student = JSON.parseObject(is, Student.class); //3.呼叫service中保存方法 new StudentService().addStudent(student); //4.通知前端保存成功 response.getWriter().print("ok"); } }
-
4、總結
匯入axios的js檔案
axios.get("url?key=value").then(r=>{ r.data });
axios.post("url","key=value").then(r=>{ r.data });
匯入vue的js檔案
在script標簽中定義vue變數
new Vue({ el:"#id值",//指定渲染的標簽 data:{},//宣告資料 methods:{},//宣告vue系結的事件方法 created(){},//頁面加載成功 mounted(){}//也可以認為是頁面加載成功 });指令:
- v-bind
- v-model
- v-on
- v-if v-else-if v-else
- v-show
- v-for
vue生命周期函式
- created或者mounted均可替代頁面加載成功
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/500841.html
標籤:其他
上一篇:svg中畫半圓
下一篇:11-ElementUI





