vue.js - 道具对象的属性在刷新函数中未定义
问题描述
我使用 Vue.js 并且有一个组件。我将一个道具“请求”传递给该组件:
<adjustments-list
v-if="request"
:request="request"
/>
在组件中,我能够做到这一点:
<text-input
:value="request.id"
/>
它的工作原理是显示“id”的值。
在组件的 props 部分:
props: {
request: Object
在组件的挂载钩子中:
async mounted () {
await this.refresh()
},
在组件的刷新功能中:
async refresh () {
console.log('this.request.id =', this.request.id)
if (this.request.id) {
const data = await requestApi.getRequestResultAdjustmentByReqId(this.request.id)
}
},
this.request.id 未定义。
我不确定为什么。
解决方案
如果该request
属性对组件是异步可用的,那么您必须使用以下观察者的组合:
// adjustments-list component
new Vue({
props: {
request: Object
},
data() {
return {
apiData: null
}
},
watch: {
request(newValue, _oldValue) {
this.refresh(newValue);
}
},
mounted: function () {
// Do something here
},
methods: {
refresh (request) {
if (request.id) {
// Using promise instead of async-await
requestApi.getRequestResultAdjustmentByReqId(request.id)
.then(() => this.apiData = data);
}
}
}
});
另外,请注意,mounted
应该是一个普通的旧 JS 函数,而不是一个async
函数。这是组件的生命周期方法,应该以特定方式运行。
推荐阅读
- android - 在达到最大参与者后,使 IMS 电话会议中的合并选项不可见
- php - 为什么我不能将输入类型日期的最小值设置为今天?
- r - fread 和 zcat 问题
- sql-server - 我怎样才能使这个 SQL 更高效
- python - 测试表格对有效数据有效,无需发布数据 django
- javascript - SyntaxError:位置 650xx 的 JSON 中的意外标记 [Char]
- scala - Spark left_outer join 正在返回两个列表中都存在的项目
- xamarin - 如何基于其中包含 StackLayout 的 Frame 创建新的 Xamarin 元素?
- spring-integration - 不支持发送,因为没有配置请求通道
- java - Java ServerSocket 防止客户端排队