Axios +Vue + themeleay

1.pom.xml

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-thymeleaf</artifactId>
 <version>2.1.15.RELEASE</version>
</dependency>

2.yml

spring:
application:
 name: ecscwapinvoice
thymeleaf:
 cache: false #關閉緩存,即便刷新 默認 true,關閉以後能夠及時刷新頁面
 mode: HTML5 #默認 HTML5
 encoding: UTF-8 # 默認  UTF-8
 prefix: classpath:/templates/ #默認 classpath:/templates/
 suffix: .html # 默認  .html
 template-resolver-order: 1 #設置視圖解析器優先級

3.HTML公共依賴抽離:

  1. 抽取公共依賴
  2. 全局axios禁用緩存
  3. 全局axios異步請求進度條
  4. 全局上下文路徑:ctx
  5. 全局加密公共JS

commonThymeleafByVue.htmljavascript

<!DOCTYPE html>
<!--suppress ALL-->
<html lang="en" xmlns:th="http://www.thymeleaf.org" th:with="unixstamp=${#dates.createNow().time}">
<head th:fragment="common_head(title,links)">
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
 <!-- 引入 Vue 和 Vant 的 JS 文件 -->
 <script th:src="@{{ctx}/NewPageByVueJs/vue.min.js(v=${#dates.createNow().time},ctx=${staticpath})}"></script>
 <!-- 引入樣式文件 -->
 <link rel="stylesheet" th:href="@{{ctx}/NewPageByVueJs/vantIndex.css(ctx=${staticpath},version=${#dates.createNow().time})}"/>
 <link rel="stylesheet" th:href="@{{ctx}/NewPageByVueJs/components.css(ctx=${staticpath},v=${#dates.createNow().time})}"/>
 <script th:src="@{{ctx}/NewPageByVueJs/vant.min.js(ctx=${staticpath},v=${#dates.createNow().time})}"></script>
 <script src="//wapcq.189.cn/static/system/js/rsa/jsencrypt.js"></script>
 <!--Axios請求-->
 <script th:src="@{{ctx}/NewPageByVueJs/axios.min.js(ctx=${staticpath},v=${#dates.createNow().time})}" type="text/javascript"
         charset="utf-8"></script>
 <!--引入加載插件-->
 <link rel="stylesheet" th:href="@{{ctx}/NewPageByVueJs/nprogress/nprogress.css(ctx=${staticpath},v=${#dates.createNow().time})}">
 <script th:src="@{{ctx}/NewPageByVueJs/nprogress/nprogress.js(ctx=${staticpath},v=${#dates.createNow().time})}" charset="utf-8"></script>
 <th:block th:replace="${links}"/>
 <title th:replace="${title}">Not Vue Static Resource</title>
 <script th:inline="javascript">
     // 本地能夠:var contentPath = [[${#httpServletRequest.getScheme() + '://' + #httpServletRequest.getServerName() + ':' + #request.getServerPort()  + #request.getContextPath() + '/'}]]
     /*<![CDATA[*/
     var contentPath = /*[[${staticpath}]]*/ 'Sebastian';
     /*]]>*/
     contentPath += "/";
     var encrypt = new JSEncrypt();

     //Axios get禁用緩存
     axios.interceptors.request.use(config => {
         /*axios攔截器,請求以前加載*/
         NProgress.start(); //開始加載狀態
         if (/get/i.test(config.method)) { // 判斷get 請求
             config.params = config.params || {};
             config.params.t = Date.parse(new Date()) / 1000;//添加時間搓
             config.headers['Cache-Control'] = 'no-cache'; //設置請求頭不緩存
         }
         if (/post/i.test(config.method)) {
             config.headers['Cache-Control'] = 'no-cache'; //設置請求頭不緩存
         }
         return config;
     }, error => {
         return Promise.reject(error);
     })

     /*axios攔截器,響應以後加載*/
     axios.interceptors.response.use(response => {
         NProgress.done();//完成以後加滿
         return response;
     }, error => {
         return Promise.reject(error);
     });
 </script>
</head>

4.Vue的JS基本生命週期:

new Vue({
    el: '#app',
    data: {
        thisInvoiceType: "",//是月結髮票仍是實繳發票
        noInvoiceList: false,//未查詢到發票
    }, created: function () {
        this.loadingImage = true;
        let InvoiceType = document.getElementById("flagByInvoice").value;
        //請求數據
        axios.get(contentPath + initUrlData)
            .then(resp => {
                this.dataHanderBYtime(resp);
            }).catch(error => {
            console.log(error)
        })
    },
    mounted() {
        document.title = this.thisInvoiceType == 1 ? '月度帳單發票' : '充值金額發票';
    },
    watch: { //循環監聽-屬性
        hebingkaipiao(newVal, oldVal) {
            console.log(newVal, oldVal)
            document.body.style.overflow= newVal ? 'hidden' : ''
        }
    },
    methods: {
        back() {
window.location.href = contentPath + "invoice/index?version=" + Math.random();
        },    
        
    }
});

5.thymeleaf+Html ModelAndView add

<div style="display: none">
 <input th:value="${invoiceType}" id="invoiceType">
</div>

6.詳細頁面使用公共組件

<html xmlns:th="http://www.thymeleaf.org">
<head th:replace="NewPageByVue/commonThymeleafByVue :: common_head(~{::title},~{})">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
    <title>開具發票</title>
</head>
    
<script th:src="@{{ctx}/NewPageByVueJs/js/InvoiceVue.js(ctx=${staticpath})}"></script>
<link rel="stylesheet" th:href="@{{ctx}/NewPageByVueJs/css/InvoiceVue.css(ctx=${staticpath})}"/>

7.axios常見使用

get請求:css

axios.get(contentPath + "invoice/new/sortVerifyIdentity", {
 params: {
     sortCode: this.inputmoder1, //驗證碼
     accNumber: this.thisSortTelSend //發送短信的號碼
 }
}).then(resp => {
 if (resp.data.success) {
     this.yzmCallbackMsg = "驗證碼輸入成功";
     this.Verification = false;//關閉彈窗
 } else {
     this.yzmCallbackMsg = "驗證碼輸入錯誤,請從新輸入!"
 }
}).catch(error => {
 console.log(error);
})

post請求:html

axios.post(contentPath + 'invoice/new/sendupdateMoreDataBySession', JSON.stringify(sendData), {
 headers: {
     "Content-TYpe": "application/json;charset=utf-8",
     "Cache-Control": "no-cache"
 }
}).then(resp => {
 if (resp.data.code == 200) {
     window.location.href = contentPath + "invoice/new/updateMoreIsTrue?version=" + Math.random();
 } else {
     this.$dialog.alert({
         message: resp.data.desc
     })
 }
}).catch(error => {
 console.log(error);

})

axios特別處理併發請求:vue

axios.all || axios.spreadjava

let arrayAxiosPostRequest = [];//併發請求數組,未知格式
for (let ii = 0; ii < thisInvoiceId.length; ii++) {
 let ThisId = thisInvoiceId[ii].id;
 let invoiceType = this.invoiceType;
 //裝配併發請求數組
 arrayAxiosPostRequest.push(this.axiosGaoBingFa(ThisId, invoiceType))
}
axios.all(arrayAxiosPostRequest).then(
 axios.spread((...resp) => {//可變 ...擴展運算符將數組變成一個參數序列
     let flagByRequest = true;//標誌位初始化定製false
     [...resp].forEach((item, index) => {
         if (!item.data.success) {
             flagByRequest = false;
         }
     });
     //若是都是成功的就跳轉
     if (flagByRequest) {
         //保存數據 : 因開票接口有延遲 : 保存這部分數據,顯示開票中
         axios.post(contentPath + "invoice/new/invoicingWaitState", this.kaipiaoInfo.data).then(resp => {
             //開票成功提示頁
             window.location.href = contentPath + "invoice/new/invoicingSuceessPage?version=" + Math.random();
         })
     } else {
         this.$dialog.alert({
             message: "開票未所有成功"
         })
     }

 })
).catch(error => {
 console.log(error)
});

axios拷貝雙向綁定的data數據ios

this.A = this.B; //會有指針綁定效應spring

**this.A = {...this.B}; //ES6 解構賦值 ||| this.A = [...this.B]; ** //深度拷貝不存在指針影響 前提是對象json

若是是字符串使用結構賦值:會把字符串解構成每一個字符的數組;axios

字符串解構:=JSON.parse(JSON.stringify(this.invoiceInfo.accNbr));api

相關文章
相關標籤/搜索