web/back + front

vue use axios in different file

qkqhxla1 2018. 9. 17. 20:30

https://forum.vuejs.org/t/putting-a-method-axios-inside-a-global-component/21729/2


axiosGet.js

export function axiosGet (url) {
  return axios.get(url)
    .then(function (response) {
        return response.data.data;
    })
    .catch(function (error) {
        return 'An error occured..' + error;
    })
}

somehtml.html

//...
<script>
    import { axiosGet } from './axiosGet'; // Filename would be axiosGet.js, you don't need the js extension when using import

    var vm = new Vue({
        el: '#app',
        data: {
            res: ''
        },
        created: function () {
            this.loadData();
        },
        methods: {
            loadData: function () {
                this.res = 'Loading ...';
                var vm = this;

                vm.res = axiosGet('http://someapicall/api/appartment');

                // OR

                axiosGet('http://someapicall/api/appartment').then(data => vm.res = data);
            }
        }
    });
</script>