ajax - 计算属性的异步调用 - 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
.
解决方案
对于您的用例,我认为计算属性不能实现目标。
我的解决方案:
- 创建一个数据属性作为一个“延迟”对象,
- 然后使用一只手表异步调用您的后端以获取新数据,最后分配给延迟对象
像下面的演示:
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>
推荐阅读
- google-apps-script - 谷歌脚本:测试谷歌表格行中是否已经存在值
- c++ - 是否可以推迟重载解决方案?
- integration - Labview 弹出请求文件夹/文件
- devexpress-mvc - Devexpress 单选按钮列表项更改颜色
- r - 将 cor.test 的结果重新格式化为数据框
- amazon-web-services - AWS Cognito 池触发器
- elasticsearch - Elasticsearch 查询消耗 100% 的 CPU
- logstash - 将字符串转换为十进制值 Logstash 变异
- html - 引导导航栏切换按钮不显示内容
- sql-server - 从多列中的多行返回结果 SQL Server