鍍金池/ 問答/HTML/ vue-resource怎么抽象在接口中使用?

vue-resource怎么抽象在接口中使用?

Thank You For Your Time!

我想將接口都模塊化出來

index-page.vue

import {
    getCarList
} from 'api/car.js';


created: function () {
    getCarList();
},

car.js

export function getCarList() {
    let url = domain + '/api/webOldCar/initNominate.action';
    this.$http.get(url).then((res) => {
        console.log(res);
    })
}

報錯說this沒有定義。我不知道在car.js中,this指向的是什么?也許是vue-resource?


Thanks for your help!

回答
編輯回答
清夢

在vue的方法里面,調用this.$http,this是指向vue組件的。在vue方法里面調用了不是vue組件內部的方法,this是不能指向到vue組件本身的。有幾種思路:

car.js改寫成這樣

import axios from 'axios'

export function getCarList() {
    let url = domain + '/api/webOldCar/initNominate.action';
    axios.get(url).then((res) => {
        console.log(res);
    })
}

getCarList方法放置到vue組件內部的method里面去

import {
    getCarList
} from 'api/car.js';


created: function () {
    this.getCarList();
},
methods: {
    getCarList: getCarList
}

以上兩種方法

2017年7月11日 04:58