Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async call for computed property - Vue.js

Tags:

ajax

vue.js

I have a computed property that will only be used if a match for a property exists. Because of this, I'm making the call to get the data asynchronous so that it's only retrieved when needed. I'm having an issue though trying to make an async call to return data for a computed property.

Below is what I have:

new Vue({
    el: "#formCompleteContainer",
    data: {
        form: {},
        components: []
    },
    computed: {
        employeeList: function () {
            var self = this;
            if (_.some(this.components, function (component) {
                return component.ComponentInfo.Type === 8
            })) {
                var employees = [];
                $.ajax({
                    url: "/Form/GetAllUsers",
                    type: "GET"
                }).done(function (results) {
                    employees = results;
                });

                return employees;
            } else {
                return [];
            }
        }
    }
});

I know this isn't working because I'm returning before the call is complete. I've seen how to use deferredobjects and what not but I can't seem to figure out how to implement it with Vue.

like image 318
Quiver Avatar asked Oct 17 '25 09:10

Quiver


1 Answers

This is what vue-async-computed is meant for. It resolves the promise you returned and handles any race conditions.

new Vue({
    el: "#formCompleteContainer",
    data: {
        form: {},
        components: []
    },
    asyncComputed: {
        employeeList: function () {
            if (_.some(this.components, function (component) {
                return component.ComponentInfo.Type === 8
            })) {
                return $.ajax({
                    url: "/Form/GetAllUsers",
                    type: "GET"
                });
            } else {
                return Promise.resolve([]);
            }
        }
    }
});
like image 52
Michael2 Avatar answered Oct 18 '25 22:10

Michael2



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!