首页 > 解决方案 > 改变 VueJS 的生命周期

问题描述

我正在使用 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');
  }
};

控制台返回两种方式如下: 控制台结果

工作流程:父创建->子创建->子挂载->父挂载<-这是我所期望的

或者

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

因此,即使代码没有改变,父子生命周期钩子也会以某种方式发生变化。

你能给我解释一下吗?

标签: vue.jslifecycle

解决方案


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


推荐阅读