Vue渲染报错:TypeError: Cannot read property 'fieldName' of undefined
Hey there, let's break down what's causing this error and get your component working properly. The TypeError: Cannot read property 'fieldName' of undefined is popping up for a few key reasons in your code—let's tackle them one by one:
1. Missing Prop Declaration
Your component tries to access this.fieldName in the created hook, but you never declared fieldName in the props option. Vue only injects explicitly defined props into the component instance, so right now this.fieldName doesn't exist at all—hence the "undefined" error.
2. Template Variable Case Mismatch
In your template, you wrote :field-name="MyFieldName", but your component's data variable is named myFieldName (lowercase "m"). Vue is case-sensitive here, so it can't find the uppercase-started variable you're referencing.
3. Syntax Errors in the Script
There are a couple of syntax bugs breaking your component:
- You used a semicolon (
;) aftername: 'myListComp'instead of a comma (,). - The
propssection has invalid syntax with... other props—props should be an object listing each prop you need explicitly.
Corrected Component Code
Here's the fixed version of your component with all these issues addressed:
Template Section
<template> <ul> <li v-for="(item, index) in componentList" :key="index" :field-name="myFieldName"> <custom_component :index="index" :some-prop="item.someProps" /> </li> </ul> </template>
Note: I added :key="index" to the v-for loop—Vue requires a unique key for list items to optimize rendering, which is a critical best practice.
Script Section
<script> export default { name: 'myListComp', props: { // Declare the fieldName prop with optional type and validation fieldName: { type: String, required: true // Mark as required if the parent component must pass it } }, data () { return { myFieldName: '', componentList: [] } }, created () { // Now this.fieldName exists because we declared it in props this.myFieldName = this.fieldName; this.componentList = this.initializeComponentList(); }, methods:{ initializeComponentList() { // Replace with your actual AJAX logic (e.g., using axios) return [ { someProps: 'First item' }, { someProps: 'Second item' }, { someProps: 'Third item' } ]; } } } </script>
Additional Tips
- If your
initializeComponentListuses asynchronous AJAX (like axios), you'll need to handle the promise properly. For example:
Then update theasync initializeComponentList() { const response = await axios.get('/your-api-endpoint'); return response.data; }createdhook to useawait:async created() { this.myFieldName = this.fieldName; this.componentList = await this.initializeComponentList(); } - Always declare props explicitly—it makes your component's API clear and helps Vue catch errors early.
内容的提问来源于stack exchange,提问作者Anand Moghe

