1. 程式人生 > 實用技巧 >Vue小知識點彙總

Vue小知識點彙總

最近接手公司前端專案,和幾個同事改了前端的程式碼,總結下整改過程中的一些經驗,方便自己,如果能幫到小夥伴們的話,那就很開心的了

1.前端呼叫後臺介面,有兩種,我們最近就調介面踩坑了,這裡記錄一下

1.1

前端程式碼(要注意請求頭):

getMsgByMobile(params) {
        return request({
            url: `${BASE_API}/mobile/common/getMsgByMobile` +
            "?mobile=" +
            params.phone +
            "&identity
=0", method: "get", headers: { "content-type": "application/x-www-form-urlencoded", }, data: params, }); },

後臺介面程式碼:

 @GetMapping("/getMsgByMobile")
 @ResponseBody
 public Object getMsgByMobile(HttpServletRequest request, String mobile, Integer identity)

1.2

前端程式碼(這裡不用請求頭):

  updateCertWayPay(params) {
        return request({
            url: `${BASE_API}/WebV2/mobile/common/updateCertWayPay`,
            method: "POST",
            data: params,
        });
    },

後臺程式碼(之前一直是通過request.getParameter("")取值,但是這次掉坑裡了,前端明明傳值了,但是後臺一直拿不到值,所以加了@RequestBody接收前端的值放到JSONObject裡,通過get的方法取值):

@RequestMapping(value = "/updateCertWayPay", method = {RequestMethod.POST})
@ResponseBody
public Object updateCertWayPay(HttpServletRequest request, HttpServletResponse httpResponse,@RequestBody JSONObject query)

2.有個需求是切換導航欄,需要根據導航欄的下拉子選項進入頁面的時候也切換到對應的選單欄,則需要監聽路由:

//子頁面監聽
watch:{
$route(to, from) {
     //to是父級呼叫子頁面時的路徑  
      this.activeName = to.query.activeName;
      this.listNewsCenterInfo(1);
    }
}

3.router-link傳引數:

:to="{path:'/newsDetail',query: {id: item.id}}"

4.子元件修改父元件的值

在子元件中需要修改父元件的資料,我們知道props傳值,具有單向性,子元件改變其值會報錯,這時候我們通過v-on繫結事件(方法名clickEvent必須和v-on定義的clickEvent一樣):

//父元件程式碼--LegalAuth子元件名稱
<LegalAuth @clickEvent="clickEvent"></LegalAuth>
//父元件程式碼-方法名(data傳進來的引數)
clickEvent(data) {
      debugger;
      this.oldAuthType = data;
      this.$route.query.authType = data;
      this.authType = data;
      if (data == 2 || data == 1 || data == 3) {
        this.isWait = true;
      }else{
        this.isWait = false;
      }
      console.log(this.oldAuthType);
    },


//子元件程式碼
this.$emit("clickEvent", 2);

5.複製內容到貼上板上,並實現換行(換行是\r\n):

copySuccess() {
      var text = "";
      text += "內容1" + "\r\n";
      text += "內容2" + "\r\n";
      text += "內容3" + "\r\n";
      text += "內容4";
      var textarea = document.createElement("textarea");
      textarea.value = text;
      document.body.appendChild(textarea);
      textarea.select();
      if (document.execCommand("copy")) {
        document.execCommand("copy");
        document.body.removeChild(textarea);
      }
      this.$message({
        showClose: true,
        message: "已成功複製到貼上板上",
        type: "success"
      });
    }

6.query傳值(引數和值會在路徑中顯示,頁面重新整理引數不會丟失)和params傳值(引數和值被隱藏,頁面重新整理引數會失效),程式碼如下:

//query(path:路徑;query:引數)
this.$router.push({
        path: "/Home",
        query: {
          cur: 0 
        }
      });
//取值
this.$route.query.cur



//params(name:路徑;params:引數)
this.$router.push({
        name: "/Home",
        params: {
          cur: 0 
        }
      });
//取值
this.$route.params.cur