【问题标题】:Changing lifecycle in VueJS改变 VueJS 的生命周期
【发布时间】:2020-10-28 04:59:36
【问题描述】:

我正在使用 VueJS 开发一个项目。我发现关于生命周期的行为有点奇怪。

我有一个名为 Profile 的父组件和一个名为 Post 的子组件。代码附在下面。

父组件:

import { ModalUserEdition, Post } from "../../components";
import { mapGetters, mapMutations, mapActions } from "vuex";
import {
  GET_PROFILE_INFO,
  GET_USER,
  EDIT_USER
} from "../../store/types/actions.type";

export default {
  // ellipsis
  
  computed: {
    ...mapGetters([
      "profile",
      "profileUserId",
      "profileUserNickname",
      "profileUserPosts",  // the elements of the list will be passed to Post component.
      "currentUserId"
    ])
  },
  methods: {
    ...mapActions([GET_PROFILE_INFO]),
    showUserEditionModal() {
      this.isShowUserEditionModal = !this.isShowUserEditionModal;
    }
  },
  created() {
    console.log('instantiated');
    console.log('profile created');
    this.getProfileInfo(this.$route.query.id);  // Vuex action
  },
  mounted() {
    console.log('profile mounted');
  }
};
<template>
    <!-- ellipsis -->

    <div class="posts">
      <post v-for="(post, index) in profileUserPosts" :key="index" :post="post"></post>
      <div class="welcome-message" v-if="profileUserPosts.length === 0">
        <!-- Some Message -->
      </div>
    </div>
  </div>
</template>

子组件:

import { mapGetters, mapActions } from "vuex";

export default {
  props: {
    post: {
      type: Object
    }
  },
  created() {
    console.log('post created');
  },
  mounted() {
    console.log('post mounted');
  }
};

Console 以两种方式返回,如下所示: Console result

工作流程: 父创建 -> 子创建 -> 子挂载 -> 父挂载

父创建->父挂载->子创建->子挂载

所以父子生命周期钩子会以某种方式改变,即使代码没有改变。

你能给我解释一下吗?

【问题讨论】:

    标签: vue.js lifecycle


    【解决方案1】:

    为什么要使用这样的生命周期?据我所知,生命周期是不能改变的,因为你在父组件中调用子组件我认为是不能实现的。

    【讨论】:

    • 我需要根据父组件中的存储状态计算派生状态以将数据传递给子组件,但是由于生命周期的变化,我无法正确传递数据,这就是我想虽然。这就是为什么我想检查生命周期是否发生变化。我同意你的观点,即生命周期不会改变。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-07
    • 2018-04-28
    • 2017-08-04
    • 1970-01-01
    • 2018-09-30
    • 1970-01-01
    • 2015-04-22
    相关资源
    最近更新 更多