首页 > 解决方案 > 计算属性的异步调用 - Vue.js

问题描述

我有一个计算属性,只有在存在属性匹配时才会使用。因此,我正在调用以获取数据asynchronous,以便仅在需要时检索它。我在尝试async调用以返回计算属性的数据时遇到问题。

以下是我所拥有的:

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 [];
            }
        }
    }
});

我知道这不起作用,因为我在通话完成之前就回来了。我已经了解了如何使用deferred对象以及未了解的内容,但我似乎无法弄清楚如何使用Vue.

标签: ajaxvue.js

解决方案


对于您的用例,我认为计算属性不能实现目标。

我的解决方案:

  1. 创建一个数据属性作为一个“延迟”对象,
  2. 然后使用一只手表异步调用您的后端以获取新数据,最后分配给延迟对象

像下面的演示:

Vue.config.productionTip = false
app = new Vue({
  el: "#app",
  data: {
    product: "Boots",
    deferedProduct: ''
  },
  watch: {
    product: function (newVal, oldVal) {
      setTimeout(() => {
        this.deferedProduct = 'Cats in ' + newVal + '!'
      }, 1500)
    }
  },
  methods: {
    nextProduct: function () {
      this.product += 'a'
    }
  }
})
<script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
<div id="app">
  <button @click="nextProduct()">Click Me!</button>
    <h2>{{product}}</h2>
    <h2>{{deferedProduct}}</h2>
</div>


推荐阅读