在ready()中访问道具属性

Accessing prop properties in ready()?

本文关键字:问道 属性 访问 ready      更新时间:2023-09-26

我在控制台得到来自ready()undefined

我正试图将值从this.users.name复制到this.userForm.name

我做错了什么?

<

概要文件用户组件/strong>

   <template>
      <input type="text" v-model="userForm.name">
   </template>
<script>
    export default {
        props: ['users'],
        ready() {
            this.userForm.name = this.users.name;
            console.log(this.users.name);
        },
        data: function () {
            return {
                userForm: {
                    name: '',
                    email: '',
                    errors: [],
                },
            }
        },
} 
</script>
HTML:

<profile-user :users="users"></profile-user>
编辑:

父值

const app = new Vue({
    el: 'body',
    data: {
        users: {}
    },
    ready: function() {
        this.fetchUser();
    },
    methods: {
        fetchUser: function() {
            this.$http.get('/api/user').then(response => this.users = response.json());
        }
    },
});

ready在Vue 2.0中已弃用。你需要使用mounted而不是ready()

从1迁移的参考。x: https://vuejs.org/guide/migration.html ready-replaced

另一个潜在的问题:你的users是一个数组项吗?如果它是一个对象,那么您可以考虑将其命名为user_info。但是,如果您将单个用户信息传递给users,并在其上添加name参数,那么您的代码应该在技术上工作。

如果你还没有vue-devtools,现在可能是在开发控制台安装和调试的好时机:https://github.com/vuejs/vue-devtools

EDIT:在问题更改后修改

感谢提供Parent组件。我想我现在看到问题了:

假设您的$http调用需要大约500毫秒才能完成。因此,父组件中的this.users在前500毫秒内是未定义的。但是你的子组件(profile-user)已经被创建了。它将尝试访问未定义的userForm.name,直到服务器响应。

为避免此问题,您可以在profile-user组件的模板中执行以下操作:

<template>
    <div v-if="userForm">
        <input type="text" v-model="userForm.name">
    </div>
    <div v-else>
        Loading user data... Please wait
    </div>
</template>

在您的开发环境中,服务器响应可能不会花费太多时间。但是this.$http调用仍然是异步的——只有在profile-user组件完全创建之后才会启动AJAX调用。