【发布时间】:2021-10-04 10:30:14
【问题描述】:
我的 Main.vue 中有两个子组件:
- 所有 cmets 的列表视图 (list-cmets)
- 单个项目视图的详细视图(列表评论)
根据 currentListView 的值,它要么显示列表,要么显示详细视图
Main.vue:这里是列表/详细视图的子组件:
<template>
<div id="list" v-if="enableListDrawer">
<list-comments
v-if="currentListView == 'comments'"
:project="project"
@showComment="showComment"
/>
<list-comment
v-else-if="currentListView == 'comment'"
:selectedComment="selectedComment"
@submitConversation="submitConversation"
/>
</div>
</template>
<script>
export default {
data() {
return {
currentListView: "comments",
selectedComment: {},
};
},
computed: {
projects() {
return this.$store.getters.projects.filter(
(o) => o._id == this.currentProjectToEdit
);
},
project() {
return this.$store.getters.projects
.filter((o) => o._id == this.currentProjectToEdit)[0]
.pages.filter((page) => page.url == window.location.href);
},
},
methods: {
showComment(comment) {
this.selectedComment = comment;
this.currentListView = "comment";
},
},
};
</script>
在 list-cmets 组件中,我正在迭代项目数组中的项目。当用户单击列表中的一条评论时,组件会向 Main.vue 发出一个事件 showComment(并从数组中传递一个项目对象)。
在 Main.vue 中,emit 触发 showComment,我将传递的对象设置为数据变量 selectedComment(我猜这是 Vue 反应性丢失的地方)。 selectedComment 绑定到列表评论组件,该组件被激活以显示详细视图。
此时,详细视图中的单个项目对象不再具有反应性。
详细视图组件,我在其中显示一条评论:
在详细视图中没有什么特别的事情发生。我不是直接修改对象
<template>
<div id="list-comment">
...
</div>
</template>
<script>
import axios from "axios";
export default {
components: {},
data() {
return {
newReply: "",
};
},
props: {
selectedComment: {
type: Object,
required: true,
},
},
methods: {
deleteConversation(id) {
this.$store.dispatch("deleteConversation", {
commentId: this.selectedComment._id,
conversationId: id,
currentProjectToEdit: "",
});
},
onSubmitConversation() {
if (this.newReply.length) {
this.$emit("submitConversation", {
pageId: "",
commentId: this.selectedComment._id,
reply: this.newReply,
});
}
},
},
};
</script>
列表视图组件,可以选择一个项目
<template>
<div id="list-comment">
<div
id="list-card"
class="list-card-hover"
v-for="(item, index) in project[0].comments"
:key="index"
@click="showComment(item)"
>
<div>{{ item.comment }}</div>
</div>
</div>
</template>
<script>
export default {
components: {},
data() {
return {};
},
props: {
project: {
type: Array,
required: true,
},
},
methods: {
showComment(item) {
this.$emit("showComment", item);
},
},
};
</script>
如何保持 Vue-App 的反应性?有什么更好的方法?
【问题讨论】:
-
您是否尝试过使用 vue devtools 来确保计算的属性在
currentListView(第一个 sn-p)中更新? -
所有计算属性都会相应更新。只是带有
selectedComment的详细视图不是响应式的。我假设selectedComment的反应性丢失了,因为我在从list-comments发出事件后将其分配给数据属性。但是我怎么能以另一种更好的方式将它传递给list-comment?实现这一点可能有更好的模式。 -
我有一个理论,我将把它作为答案发布,如果不正确请告诉我
标签: javascript vue.js vue-component vuex vue-props