【问题标题】:Vue Class Component property not defined on instanceVue 类组件属性未在实例上定义
【发布时间】:2021-03-18 02:00:36
【问题描述】:

我遇到的问题是,在应用程序从服务器后端获取一些数据后,我的 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]: Property "restaurant" was accessed during render but is not defined on instance.v-if 上我觉得很奇怪,因为这就是它存在的确切原因。我需要如何初始化餐厅,使通过axios的更新被vue正确识别?

【问题讨论】:

    标签: javascript typescript vue.js vue-component vue-class-components


    【解决方案1】:

    尝试使用 Typescript unionnull

    restaurant: Restaurant | null = null;
    

    来自 Vue 类组件docs

    请注意,如果初始值未定义,则类属性将不会被响应,这意味着不会检测到属性的更改

    为避免这种情况,您可以使用空值或使用数据挂钩:

    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
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-07-17
      • 2020-02-03
      • 2018-02-27
      • 2019-09-08
      • 1970-01-01
      • 2018-12-10
      • 1970-01-01
      • 2018-04-14
      • 2020-07-14
      相关资源
      最近更新 更多