前几篇介绍了 Vuex 管理资料状态,以及在生命周期或导航守卫发送 API 的时机点,再次回到专案范例,目前已处理好显示导览列中的全部书单内容,我们接续完成其他导览项目所需要的画面资料。
action 发送 API 後将资料以 commit
呼叫 mutation
actions: {
async fetchBookList(context) {
const books = await GET();
context.commit("bookList", books);
},
},
mutation 将资料直送并赋值给 state
state: {
bookList: {},
},
mutations: {
bookList(state, books) {
state.bookList = books;
},
},
getters 取得 state 资料
方式一:从 state 拿取同一份资料,再各别进行资料处理
getters: {
allBooks: (state) => state.bookList.list,
discount30Books: (state) =>
state.bookList.list.filter(
(book) =>
0.7 <= book.sellPrice / book.originPrice &&
book.sellPrice / book.originPrice < 0.8
),
discount50Books: (state) =>
state.bookList.list.filter(
(book) =>
0.5 <= book.sellPrice / book.originPrice &&
book.sellPrice / book.originPrice < 0.6
),
ithelpBook: (state) =>
state.bookList.list.filter((book) => book.name.includes("铁人赛")),
},
方式二:透过拿取其他 getters 再加工处理,当遇到重复的筛选条件也可合并为一个共用函式加以简化
getters: {
allBooks: (state) => state.bookList.list,
discountBooks: (state, getters) => (min, max) =>
getters.allBooks.filter(
(book) =>
min <= book.sellPrice / book.originPrice &&
book.sellPrice / book.originPrice < max
),
discount30Books: (state, getters) => getters.discountBooks(0.7, 0.8),
discount50Books: (state, getters) => getters.discountBooks(0.5, 0.6),
ithelpBook: (state, getters) =>
getters["allBooks"].filter((book) => book.name.includes("铁人赛")),
}
最後,在元件内的 computed 取用 getters 的资料
computed: {
books() {
return this.$store.getters["allBooks"];
},
},
以上算是发送 API 和资料处理的基本流程方向,但因应每个人的开发习惯多少还是会有差异。有些人的作法可能会根据资料的共用范围决定处理资料的时间点:
目前的做法会是统一都在 getters 处理资料,因此在元件内只需单纯取用 getter 即可,如此一来我将所有的复杂逻辑集中在 getters 做好管理,当资料有任何错误情形发生时,就不用再回想资料有没有共用情形、当初是放在哪一边处理逻辑等琐碎问题,而来回在 getters 和 computed 之间检查程序码。
回到 Vuex 的开头以 dispatch
呼叫 action,选择在适合的导航守卫位置发送 API。
全域 beforeEach
发送 API:看似快速又方便,但是进入其他不需要书单资料的页面时也会跟着发送 API。
router.beforeEach(async (to, from, next) => {
await store.dispatch("fetchBookList");
next();
});
路由 beforeEnter
发送 API:将导览项目路由规划成巢状结构,直接在父层路由发送 API。
{
path: "/book",
redirect: { name: "All" },
component: MainPage,
beforeEnter: async (to, from, next) => {
await store.dispatch("fetchBookList");
next();
},
children: [
{
path: "all",
name: "All",
component: All,
},
... // 略
],
},
在页面中新增显示书单笔数。
切换导览项目时,能更明显确认不同页面所串接的资料差异。
由於所有导览项目页面内的排版一致,因此可将排版另外包成一个元件,之後也会陆续介绍元件之间传递资料的方式。
>>: Day21 NiFi - 与 GCP BigQuery 对接设定
上次练习了变数的宣告以及如何使用变数去做简单的相加 这次则是要用cin这个指令 结合过去所学到的做几...
完善的资料库能够有效地存储数据,提供最新、最精确的资讯,满足使用者的应用需求,因此正确的资料库结构设...
什麽是抽象类别 an abstract class, or abstract base class ...
今天要跟大家介绍 在 ubuntu 安装 Zabbix Agent 时,设定的 Template O...
最後一天!礼拜五快乐!恭喜大家完赛!恭喜自己XD 今天来回头看看我们这三十天学了哪些事,还有讲一下未...