1. 程式人生 > >vue axios前後端資料互動問題(2)

vue axios前後端資料互動問題(2)

前一篇的介紹中遺留了幾個問題,而且部分內容即success、error那部分有誤,具體內容以本篇的為主。本篇解決的問題如下:

問題:1、後臺獲取前端資料的值;

         2、前端渲染接收到的後臺的值;

         3、在axios中this的指向問題。

1、後臺獲取到前臺的值,首先在main.js中配置以下檔案

import axios from 'axios'

import qs from 'qs'

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

Vue.prototype.$qs = qs

Vue.prototype.$ajax = axios
axios.interceptors.request.use((config) => {
    config.data = qs.stringify(config.data);
    return config;
}, function(error) {
    return Promise.reject(error);
});

2、前端渲染接收到的後臺的值

  (1) 在data中定義一個:

    errorinfo:'',

  (2)在呼叫axios接收後臺返回的值的地方使用this.errorinfo="後臺獲取的值"

 完成上述步驟後會出現一個this的指向問題,接著看3的解決辦法。

3、在axios中this的指向問題

   要使在axios中的this指向這個vue中的 errorinfo,就要採用ES6的語法=>來寫接收成功的那一部分內容。

完整的例子如下:

<span class="error_tip">{{errorinfo}}</span> 

<div class="form_item">

<input type="text" :style="test"  v-model="user" placeholder="請輸入帳號" @blur="validataPhone(user)"/>

</div>

data中的資料:

      return {user:'',errorinfo:''}

method中呼叫的方法:

      this.$ajax({

                    method: 'post',
                    url : "http://IP:8088/demo/user/login.do",
                    data : {
                        "後臺的值": 前臺的值
                    }

                })//   如果直接在裡面訪問 this,無法訪問到 Vue 例項,this指向發生了變化。建議使用箭頭函式,下面有講

                //請求成功後執行then

        .then((response)=> {

       console.log(response);   //處理後臺返回的資料
       var result = response ;
       var id=result.data.data.id; //獲取對應的資料,賦值給id
       this.errorinfo=id;   // 將id的值給指向這個vue例項的errorinfo,實現頁面的渲染

    })

               //請求失敗後執行catch

   .catch(function(err){
       console.log(err)
    }) ;