Запустите код vuejs после завершения всех запросов axios - PullRequest
0 голосов
/ 03 января 2019

Здесь мне нужно запустить функцию carResult только после того, как все запросы axios будут выполнены. Добавление его в метод method2 не сработает, так как компонент выполняет код дважды. Было бы здорово помочь, если бы кто-нибудь помог мне с кодом vue, который работает после всех запросов axios.

<html>
    <head>
        <title>title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </style>
</head>
<body>
    <div id="el">
        <div>
            <p>Selected: {{ input.selected }}</p>
            <select2 :options="options" v-model="input.selected">
                <option disabled value="0">Select one</option>
            </select2>
        </div>
        <div>
            <p>Selected: {{ input.selected2 }}</p>
            <select2 :options="options2" v-model="input.selected2">
                <option disabled value="0">Select one</option>
            </select2>
        </div>
    </div>
    <script type="text/x-template" id="select2-template">
        <select>
        <slot></slot>
        </select>
    </script>
    <script src="http://themestarz.net/html/craigs/assets/js/jquery-3.3.1.min.js"></script>
    <script src="https://unpkg.com/vue@2.5.17/dist/vue.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script>
Vue.component('select2', {
    props: ['options', 'value'],
    template: '#select2-template',
    mounted: function () {
        var vm = this;
        $(this.$el)
                // init select2
                .select2({data: this.options})
                .val(this.value)
                .trigger('change')
                // emit event on change.
                .on('change', function () {
                    vm.$emit('input', this.value)
                })
    },
    watch: {
        options: function (options) {
            // update options
            $(this.$el).empty().select2({data: options})
        },
        value: function (value) {
            // update value
            $(this.$el)
                    .val(value)
                    .trigger('change')
        }
    },
    destroyed: function () {
        $(this.$el).off().select2('destroy')
    }
});

var vm = new Vue({
    el: '#el',
    data: {
        input: {
            selected2: "all",
            selected: "all"
        },
        options: [],
        options2: [],
        items: []
    },
    created: function () {
        this.mymethod();
    },
    watch: {
        input: {
            handler(newInput) {
                this.carResult(); 
            },
            deep: true
        },
        itemsArray() {
            this.setPages();
        }
    },
    methods: {
        mymethod: function () {
            var vm = this;
            axios.get('https://api.coindesk.com/v1/bpi/currentprice.json')
                    .then(function (response) {
                        vm.options = [
                            {id: 0, text: 'All'},
                            {id: 1, text: 'Hello'},
                            {id: 2, text: 'World'},
                            {id: 3, text: 'Bye'}
                        ];
                        vm.input.selected = 2;
                        vm.method2();
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
        },
        method2: function () {
            var vm = this;
            axios.get('https://api.coindesk.com/v1/bpi/currentprice.json')
                    .then(function (response) {
                        vm.options2 = [
                            {id: 0, text: 'All'},
                            {id: 1, text: 'This'},
                            {id: 2, text: 'is'},
                            {id: 3, text: 'second'}
                        ];
                        vm.input.selected2 = 2;
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
        },
        carResult: function () {
            var vm = this;
            axios.get('https://api.coindesk.com/v1/bpi/currentprice.json')
                    .then(function (response) {
                        vm.items = response.data;
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
        }
    }
});
    </script>
</body>
</html>

1 Ответ

0 голосов
/ 03 января 2019

Передайте все ваши вызовы axios на Promise.all(), который разрешится после того, как все вызовы axios были сделаны.

Promise.all([axios.get(url1), axios.get(url2), axios.get(url3)])
  .then((allResults) => {
    console.log("All axios calls have been made!")
})

Promise.all() требует массив обещаний в качестве аргумента, а метод axios.get() возвращает обещание.

Все возвращаемые значения из Promise.all() будут в порядке пропущенных Обещаний, независимо от порядка выполнения.

Дополнительная информация: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...