【问题标题】:Vue Js Composition Api undefined (reading 'name')Vue Js Composition Api 未定义(读取\'name\')
【发布时间】:2022-08-08 15:43:09
【问题描述】:

我在尝试使用组合 API 时遇到了 undefine (destination.name),但是当我使用选项 API 时,代码或计算属性正在工作并且我没有收到任何错误。有人能帮我吗?谢谢

<template>
  <section class=\"destination\">
    <h1>{{ destination.name }}</h1>
  </section>
</template>

<script setup>
/*
  import
*/
import { useRoute, useRouter } from \"vue-router\";
import { computed } from \"vue\";
import sourceData from \"@/travel-data/data.json\";

/*
  use params from vue-router
*/
const route = useRoute();
const router = useRouter();

const destinationId = computed(() => {
  return parseInt(route.params.id);
});

const destination = computed(() => {
  return sourceData.destinations.find(
    (destination) => destination.id === destinationId
  );
});
</script>

错误

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading \'name\')
    at Proxy._sfc_render (DestinationView.vue:3:24)
    at renderComponentRoot (runtime-core.esm-bundler.js:896:44)
    at ReactiveEffect.componentUpdateFn [as fn] (runtime-core.esm-bundler.js:5580:57)
    at ReactiveEffect.run (reactivity.esm-bundler.js:185:25)
    at instance.update (runtime-core.esm-bundler.js:5694:56)
    at setupRenderEffect (runtime-core.esm-bundler.js:5708:9)
    at mountComponent (runtime-core.esm-bundler.js:5490:9)
    at processComponent (runtime-core.esm-bundler.js:5448:17)
    at patch (runtime-core.esm-bundler.js:5038:21)
    at ReactiveEffect.componentUpdateFn [as fn] (runtime-core.esm-bundler.js:5660:17)

enter image description here

    标签: vue.js


    【解决方案1】:

    使用v-if 添加条件渲染,并在比较中使用值字段访问destinationId 属性:

    <template>
      <section class="destination">
        <h1 v-if="destination">{{ destination.name }}</h1>
      </section>
    </template>
    
    <script setup>
    /*
      import
    */
    import { useRoute, useRouter } from "vue-router";
    import { computed } from "vue";
    import sourceData from "@/travel-data/data.json";
    
    /*
      use params from vue-router
    */
    const route = useRoute();
    const router = useRouter();
    
    const destinationId = computed(() => {
      return parseInt(route.params.id);
    });
    
    const destination = computed(() => {
      return sourceData.destinations.find(
        (destination) => destination.id === destinationId.value
      );
    });
    </script>
    

    【讨论】:

      【解决方案2】:

      尝试做这个空检查

      <h1>{{ destination ? destination.name : '' }}</h1>
      

      【讨论】:

        猜你喜欢
        • 2021-04-26
        • 2020-11-12
        • 2017-04-21
        • 1970-01-01
        • 2020-10-09
        • 2021-08-28
        • 1970-01-01
        • 2020-11-11
        • 2020-08-08
        相关资源
        最近更新 更多