为什么 Vue 在使用 vue router 传递 props 时出现 Cannot read properties of undefined 的类型错误

why is Vue giving a type error of Cannot read properties of undefined when passing props using vue router

提问人:damilola david 提问时间:11/8/2023 最后编辑:damilola david 更新时间:11/9/2023 访问量:33

问:

在使用 vue router 时,我试图为我的组件获取一个道具,但它一直给出错误“无法读取未定义的属性(读取'subjectName')”控制台图像

我的路由器JS文件

const router =createRouter({
    history:createWebHistory(),
    routes:[
        {path:'/', component:indexPage }
       {path:'/subject/:subName', component:subjectPage, props:true},
       {path :"/login", component:thePage, 
    },
    {path :"/register", component:signUp,},
    ]
})

在这里,我使用 Provide 和 Injection 从父组件获取数据。

export default {
  props:['subName'],
  inject: ["subjects"],
  data() {
    return {
      subjectName: "",
      subjectImage: "",
    };
  },
  methods: {
    loadSubject(subName) {
      const pickedSubject = this.subjects.find((subject)=>subject.subjectName===subName);
      this.subjectName=pickedSubject.subjectName;
      this.subjectImage=pickedSubject.subjectImage;
    },
  },
  created() {
    this.loadSubject(this.subName);
  },
  watch: {
    subName(newSubject) {
      this.loadSubject(newSubject);
    },
  },
};

这是 SUBJECTPAGE VUE 文件

<template>
  <heroSection></heroSection>
  <courseOutline></courseOutline>
</template>
<script>
import heroSection from "./heroSection.vue";
import courseOutline from "./courseOutline.vue";
export default {
  data() {
    return {
      subjects: [
      {
          subjectName: "biology",
          subjectDescription: "some random text",
          subjectGoals: ["four", "five", "six"],
          subjectImage: "../../../IMAGES/sixteen.jpg",
        },
      ],
    };
  },
  components: {
    heroSection,
    courseOutline,
  },
  provide() {
    return {
      subjects: this.subjects,
    };
  },
};
</script>

javascript vue.js 框架 javascript-objects 路由器

评论

0赞 Phil 11/8/2023
您的“router js”文件不是有效的 JavaScript,因此不可能正在使用
0赞 Phil 11/8/2023
至于您的特定错误,似乎很明显,它是由于您不匹配数组中的任何内容而引起的,因此未定义。您是否尝试过调试数组中的属性和 中的值?find()subjectspickedSubjectsubjectNamesubjectssubName
0赞 Jaromanda X 11/8/2023
也许在组件中显示相关代码 - 如文档所述subjectPage// make sure to add a prop named exactly like the route param
0赞 damilola david 11/9/2023
我认为问题是 vue router 没有将 prop 传递给 X @Jaromanda组件
0赞 Jaromanda X 11/9/2023
没有看到你的我只能猜测,你可以知道subjectPage

答: 暂无答案