gpt4 book ai didi

javascript - Vue 类组件属性未在实例上定义

转载 作者:行者123 更新时间:2023-12-02 19:05:04 26 4
gpt4 key购买 nike

我遇到的问题是,在应用程序从服务器后端获取一些数据后,我的 UI 无法更新。

我有以下代码:

<template>
<div v-if="restaurant">
<div class="center logo-container">
<img class="img-fit" v-bind:src="'/api/restaurant/logo/' + restaurant.id" alt=""/>
</div>
<h2 class="title center dm-text-header">{{ restaurant.name }}</h2>
<h4 class="subheading center">{{ restaurant.address.street }}, {{ restaurant.address.city }}</h4>
</div>
</template>

<script lang="ts">
import axios from 'axios';
import { Options, Vue } from "vue-class-component";
import { Tag } from "./Tag";
import { Restaurant } from "./Restaurant";

@Options({
props: {
}
})
export default class Menu extends Vue {
// hardcoded for testing
restaurantId = "8ykw9ljq";

tagUrl = "/api/menu/" + this.restaurantId + "/tags";
restaurantUrl = "/api/restaurant/" + this.restaurantId;

restaurant!: Restaurant;
tags: Tag[] = [];

mounted() {
// get tags
this.getTags();
// get restaurant
this.getRestaurant();
}

getRestaurant(): void {
axios.get<Restaurant>(this.restaurantUrl)
.then(res => {
this.restaurant = res.data;
});
}

getTags(): void {
axios.get(this.tagUrl)
.then(res => {
this.tags = res.data;
});
}

}
</script>

我验证了后端确实为正确的餐厅提供服务,并在 axios 调用完成后记录了结果。问题是 DOM 没有更新。如果我将以下内容添加到 DOM 中,则会更新:

<template>
...
<div>
{{tags}}
</div>
<template>

在我看来,vue 仅在识别到已初始化的空数组的更改而不是当前未初始化的餐厅对象时才更新 DOM。

我进一步收到警告:[Vue warn]: 属性“restaurant”在渲染期间被访问,但未在实例上定义。v-if 上我觉得很奇怪,因为那是确切的它存在的原因。我需要如何初始化餐厅,以便 vue 正确识别通过 axios 进行的更新?

最佳答案

尝试 typescript unionnull:

restaurant: Restaurant | null = null;

来自 Vue 类组件 docs :

Note that if the initial value is undefined, the class property will not be reactive which means the changes for the properties will not be detected

To avoid this, you can use null value or use data hook instead:

import Vue from 'vue'
import Component from 'vue-class-component'

@Component
export default class HelloWorld extends Vue {
// `message` will be reactive with `null` value
message = null

// See Hooks section for details about `data` hook inside class.
data() {
return {
// `hello` will be reactive as it is declared via `data` hook.
hello: undefined
}
}
}

关于javascript - Vue 类组件属性未在实例上定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65170280/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com