programing

Vue js에서 axios 메서드를 가져오기 위한 올바른 구문

prostudy 2022. 3. 9. 10:36
반응형

Vue js에서 axios 메서드를 가져오기 위한 올바른 구문

나는 생성된 후크에서 직접 전화를 걸지 않고 주 vue 인스턴스를 가져와 내 공리 호출과 분리하려고 한다.

data.js라는 별도의 파일에 이것을 가지고 있다.

import axios from 'axios'
export default{
    myData() {
        return axios.get(`http://localhost:8080/data.json`)
            .then(response => {
                // JSON responses are automatically parsed.
                return response.data;
            })
            .catch(e => {
                return this.myErrors.push(e)
            });
},

그리고 나의 예를 들어 다음과 같은 것이 있다.

import myDataApi from '@/api/data.js'

export default {
    name: 'app',
    components: {
        myDataApi, // not sure if this is correct
    },
    data: function () {
        return {
            myInfo: '',
        }
    },
    created() {
        this.myInfo = myDataApi.myData();
        console.log('this.myInfo= ', this.myInfo)
    },

myInfo에 myData라는 json을 채우려고 한다.이것이 돌아온다.[object Promise]Vue devtools 및 에서Promise {<pending>}콘솔에

내가 필요한 모든 데이터는 그 안에 있다.Promise {<pending>}라고 하는 배열로[[PromiseValue]]:Object효과가 있다는 걸 알고 있어 정확한 구현 방법을 알고 싶을 뿐이야

현재 테스트할 수 있는 개발 환경은 없지만 구성 요소가 초기화되는 순간 변수를 할당하려고 하는 것이 눈에 띈다.이 물체는 약속이지만, 당신이 가져온 부품 안에서 해결된 후에는 당신은 약속을 처리하지 않는다.

나는 실제 구성 요소 안에서 약속을 처리하도록 노력하기를 권한다. 예를 들면 다음과 같다.

import myDataApi from '@/api/data.js'

export default {
    name: 'app',
    components: {
        myDataApi, // not sure if this is correct
    },
    data: function () {
        return {
            myInfo: '',
        }
    },
    created() {
        myDataApi.myData()
          .then((data) => {
            this.myInfo = data
            console.log('this.myInfo= ', this.myInfo);
          });
          .catch((e) => handleError) // however you want to handle it

    },

단지 @LExJacobs의 대답에 덧붙여 말하자면.아래와 같이 .c)의 데이터 주변의 괄호를 생략했다.Vue는 데이터가 있어도 이용할 수 없다고 투덜거렸다.솔직히 말하면 왜 그런지 모르겠지만, 이것은 그 문제를 해결했다.

myDataApi.myData()
    .then(data => {
        this.dataHasLoaded = true;
        this.myInfo = data;
    })
    .catch(e => {
        this.myErrors.push(e)
    });

참조URL: https://stackoverflow.com/questions/50901701/correct-syntax-for-importing-axios-method-in-vue-js

반응형