11.Vue安裝Axios及使用


1.安裝:npm install axios --save-dev


2.main.js中導入
  import axios from 'axios'; /* 引入axios進行地址訪問*/
  Vue.prototype.$http = axios;
  (注意:不使用use來使用該例,而是用prototype原型來使用)

3.login.vue中:
  import axios from 'axios';

  axios.post("/api/login?", params).then(function(res) {
    var data = res.data;
    // console.log(data);
    let role = data.result.user.role;
    let token = data.result.token;
    localStorage.setItem("currentUser_token", token); //將token存到本地的localStorage中
    // console.log(localStorage);
    if (data.code == 1) {
    alert(data.msg);
    let _username;
    // console.log(localStorage.getItem("currentUser_token"))
    // console.log(userName)
    that.$router.push({path: "/index",query: { name: userName, role: role }}); //跳轉到 index頁面中並傳遞name和role的值

    (在index頁面中接受參數:PS:let userName = this.$route.query.name;let userRole = this.$route.query.role;)

  } else {

    alert(data.msg);
  }
  }).catch(function(err) {
    console.log("LOGIN_" + err);
  });
(注意:若要使用全局路徑訪問請求則需要在config中的index.js中配置proxyTable)
舉例:proxyTable: {
    '/api': {
      target: 'IP+端口', //后端接口地址
      changeOrigin: true, //是否允許跨越
      pathRewrite: {
      '^/api': '/api', //重寫,
      }
     }
   },


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM