当我try 使用组合API时,我有未定义的(estination.name),但当我使用Options API时,代码或计算(computed)属性正在工作,并且我没有收到任何错误.有人能帮我吗?谢谢

<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) Type误差率: 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

推荐答案

在比较中添加带有v-if的条件呈现和带有值的Access 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>

Vue.js相关问答推荐

vue3 输入标签给出错误 Vue.use 不是函数

如何 for each 动态创建的按钮/文本字段设置唯一变量?

如何在 v-for 指令切换状态下安全地制作包含附加到对象的复选框的列表(W/O 切换列表中的其他复选框)?

如何在 vue js 的一页路由下显示不同的 category._id

如何使用 async/await 在 vue js 中添加标头

Vue index.html favicon 问题

Vue-router:循环路由以动态创建

如何在 vue.js 2 的其他组件中调用方法?

如何在 vue.js 中包含当年的版权?

如何将参数传递给使用 ...mapActions(...) 映射的函数?

Vue路由安全

'不提供名为'createRouter'的导出'' vue 3、vite 和 vue-router

中文而不是英文的Element UI分页

vue-cli-service build --target lib 导入为 lib 时丢失图像路径

Vue.js 的 $emit 和 $dispatch 有什么区别?

Vue.js react性如何在幕后工作?

VueJS 复选框更新

Vue.js 和 jQuery datepicker/timepicker 双向绑定

如何在布局中使用组件?

在 vue.js 应用程序中将静态内容(例如国家代码)存储在哪里?