问题
✅ Vue 2: 计算属性在 vuex 存储突变后更新。
❌ Vue 3: 计算属性在 vuex 存储突变后不会更新。
Vuex 4
目的:从 Firestore 获取帖子。添加到“postsArray”。提交突变。
注意:函数“getNextPosts”是从允许无限滚动的(工作)交叉点观察者调用的。
const postsArray: Array<string> = [];
const vuexStore = createStore({
state: {
posts: []
},
actions: {
// See https://firebase.google.com/docs/firestore/query-data/query-cursors#paginate_a_query
getFirstPosts({ commit }) {
const getFirstPosts = async () => {
const firstPostsQuery = firestore.collection("posts").limit(3);
// Get FIRST posts.
const firstPosts = await firstPostsQuery.get();
// Add to postsArray.
for (const doc of firstPosts.docs) {
postsArray.push(doc.id);
}
// Add to vuex store.
commit("addFirstPostsToVuex", postsArray);
// Set reference.
lastPostDownloaded = firstPosts.docs[2]; // 3rd post.
};
getFirstPosts();
},
getNextPosts({ commit }) {
const getNextPosts = async () => {
const nextPostsQuery = firestore
.collection("posts")
.startAfter(lastPostDownloaded)
.limit(2);
// Get NEXT posts.
const nextPosts = await nextPostsQuery.get();
// Add to postsArray.
for (const doc of nextPosts.docs) {
postsArray.push(doc.id);
}
// Add to vuex store.
commit("addNextPostsToVuex", postsArray);
// Update reference.
lastPostDownloaded = nextPosts.docs[1]; // 2nd post.
};
getNextPosts();
}
},
mutations: {
addFirstPostsToVuex(state, value) {
state.posts = value;
},
addNextPostsToVuex(state, value) {
state.posts = value;
}
}
});
计算属性
export default ({
computed: {
posts() {
// List rendering.
return vuexStore.state.posts;
}
}
});
v-for
<template>
<div id="feed">
<article class="post" v-for="post in posts" v-bind:key="post.id">
<header class="info">
{{ post }}
</header>
</article>
</div>
</template>