Vue组件中prop已存在于this对象但方法内无法访问的问题
groupId Showing as false in Mounted Hook Let's break down what's happening here and fix this issue step by step:
First, Let's Clarify the Core Problem
You mentioned Vue Devtools shows the prop exists, but console.log(this.groupId) in mounted outputs false. This almost always means:
The
group_idvalue in your parent component is initially set tofalse, and gets updated to the correct value after the child component'smountedhook runs. Devtools shows the latest updated value, but yourmountedlog only captures the initialfalse.
Fix 1: Watch for Prop Changes (Best for Async Data)
If your parent component's group_id comes from an async source (like an API call or route params), it won't be ready when the child mounts. Instead of relying solely on mounted, add a watcher to trigger fetchGroup whenever groupId updates to a valid value:
export default { // ... rest of your component code watch: { groupId(newVal) { // Only run when we get a valid non-false value if (newVal) { this.fetchGroup(); } } }, mounted() { // Fallback: run once if groupId is already valid on mount if (this.groupId) { this.fetchGroup(); } } }
Fix 2: Delay Child Component Render Until Prop is Valid
If you want the child component to only mount after group_id has a valid value, add a v-if to the parent's component call:
<friend-create-form v-if="group_id" v-bind:group-id="group_id"></friend-create-form>
This way, the child will only be created when group_id is truthy, so mounted will immediately have the correct value.
Fix 3: Double-Check Spelling (And Avoid That Syntax Error)
The ${this.groupid} attempt failed because of a spelling mistake: your prop is named groupId (capital D), but you wrote groupid (lowercase d). In script code, always use the exact camelCase name you defined in the props array.
Quick Check: Verify Parent Component's Initial Value
Take a look at your parent component's data definition. If it looks like this, that's the source of the initial false:
data() { return { group_id: false // Initial value is false, gets updated later } }
This is totally normal for async data, but it explains why your mounted log shows false even though Devtools has the correct value later.
内容的提问来源于stack exchange,提问作者sveti petar

