Vue-cli中Props数据绑定问题:属性未定义及非响应式报错
Hey Carlos, let's tackle those prop warnings you're hitting! The issue is straightforward: your Book.vue component is trying to use author and complete in its template, but Vue doesn't recognize them as reactive properties because you haven't properly declared them as props (or passed them from the parent App.vue component). Let's walk through the fix step by step:
1. Declare Props in Book.vue
First, you need to explicitly tell your Book.vue component that it expects to receive author and complete from its parent. This registers the properties as reactive and eliminates the "not defined on instance" warning.
<!-- src/components/Book.vue --> <template> <div class="book-item"> <h4>Author: {{ author }}</h4> <p>Status: {{ complete ? "Completed" : "In Progress" }}</p> </div> </template> <script> export default { name: "Book", // Declare the props your component needs props: { author: { type: String, required: true // Mark as required if this value must be provided }, complete: { type: Boolean, default: false // Set a fallback value if parent doesn't pass it } } }; </script>
2. Pass Props from App.vue to Book.vue
Next, you need to pass the actual values for author and complete from your parent App.vue component to Book.vue. Use Vue's binding syntax (: prefix) to pass reactive data instead of static strings.
<!-- src/App.vue --> <template> <div id="app"> <h1>My Reading List</h1> <!-- Loop through your books and pass props to each Book component --> <Book v-for="book in readingList" :key="book.id" :author="book.author" :complete="book.complete" /> </div> </template> <script> import Book from "./components/Book.vue"; export default { name: "App", components: { Book }, data() { return { readingList: [ { id: 1, author: "Harper Lee", complete: true }, { id: 2, author: "Neil Gaiman", complete: false }, { id: 3, author: "Octavia Butler", complete: true } ] }; } }; </script>
Why This Works
Vue throws that warning because it can't find author or complete in the component's data, computed, or props options. By declaring them in the props object of Book.vue, you're telling Vue these properties come from the parent component and should be treated as reactive. The binding syntax in App.vue ensures the parent's data is passed down correctly.
内容的提问来源于stack exchange,提问作者Carlos Gómez

