【发布时间】: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
工作流程: 父创建 -> 子创建 -> 子挂载 -> 父挂载
或
父创建->父挂载->子创建->子挂载
所以父子生命周期钩子会以某种方式改变,即使代码没有改变。
你能给我解释一下吗?
【问题讨论】: