javascript - Mounted in child component executes before parent component created 问题

标签 javascript vue.js components

我正在开发 vue 应用程序。我在这里面临的问题是挂载的子组件在创建父子组件之前执行。

我正在将 props 从父组件发送到子组件,我想在子组件的挂载中使用这些 props,但我没有将这些 props 挂载,因为它们是在父组件中创建之前执行的。请帮我解决这个问题,以便子组件将 this.userCopy 设置为作为 Prop 出现的 this.user。

父组件

<template>
 <div>
  <Info :user="user" />
 </div>
</template>
<script>
 import Info from 'views/info';
 export default {
  components: {
    Info
  },
  data () {
    return {
      user: {
        first_name: '',
        last_name: '',

      },
      errors:[]
    }
  }
  created() {
    this.fetchUsers();
  },
  methods: {
   fetchUsers() {
      this.$axios.get('/user.json')
      .then(response => {
          this.user = response.data;
          

      }).catch(error => {
        this.errors = error.response.data.error;
      });
    },
  }
 }
 </script>

子组件

<template>
 <div>
  {{userCopy}}
 </div>
</template>
<script>
 export default {
  props: ['user'],
  data () {
    return {
      userCopy: {}
    }
  }
  mounted: function() {
   var that = this;
   this.userCopy = this.user
  }
 }
</script>

最佳答案

由于 user 在组件已经挂载后异步更新,因此 user 将是 mounted() 中的初始值(未定义)钩子(Hook)。

选项 1: parent 可以 conditionally render基于 user 的子组件,这样组件的 user prop 在挂载时会有一个值:

<Info v-if="user" :user="user">
export default {
  data() {
    return {
      user: null, // updated asynchronously in fetchUsers()
    }
  }
}

选项 2: child 可以使用 watcher在更新 userCopyuser 上:

export default {
  //...
  watch: {
    user(user) {
      this.userCopy = { ...user } // shallow copy
    }
  }
}

注意 spread operator 的使用浅拷贝 user

关于javascript - Mounted in child component executes before parent component created 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66996295/

相关文章:

javascript - Haxe - 找不到类 : Main

javascript - Facebook FB.ui oauth 在 Canvas 页面上弹出

javascript - 从集合中移除绑定(bind)以从 View 中移除

node.js - vue build 崩溃 ubuntu 18.04

webpack - SyntaxError : expected expression, 得到 '<' 错误 - vue

reactjs - react this.props 未定义或空对象

javascript - 文本甚至不使用 typed.js 输入

firebase - VueJS + VUEX + Firebase : Where To Hook Up Firebase?

javascript - React.createElement : type should not be null

javascript - ReactJS-错误 : Objects are not valid as a React child