Vue(Vue3取代 Vuex?)
哎呀,以前在資料管理的部分都被Vuex綁死死,但是在typescript相對來說是很不友善的(我有寫一篇for vuex在typescript 去定義),自從我用了vue3 的composition API及reactive 就直接使用了 yarn remove vuex
,在typescript的世界裡就是要清清楚楚,簡簡單單,甚麼模板轉換的才不需要呢
我們來創自己管資料的地方吧
type.ts:
export interface InterComicsData extends InterGenre {
id: string;
mainIndex: string;
mainIndex_name: string;
descr: string;
link: string;
title: string;
thumbnail_name: string;
thumbnail_url: string;
lastUpdateTime: string;
createTime: string;
genreDatas: InterGenre[];
}
export interface InterGenre {
id: string;
rootComics_id: string;
name: string;
}
export interface InterComics {
comicDatas: InterComicsData[];
genreDatas: InterGenre[];
pageLimit: Number;
}
export interface InterComicsData extends InterGenre {
id: string;
mainIndex: string;
mainIndex_name: string;
descr: string;
link: string;
title: string;
thumbnail_name: string;
thumbnail_url: string;
lastUpdateTime: string;
createTime: string;
genreDatas: InterGenre[];
}
export interface InterGenre {
id: string;
rootComics_id: string;
name: string;
}
export interface InterComics {
comicDatas: InterComicsData[];
genreDatas: InterGenre[];
pageLimit: Number;
}
comics.ts:
我有做一個漫畫站,這邊是用來管理comics的地方
import Vue, { reactive, defineComponent, readonly } from "vue";
import { InterComicsData, InterComics, InterGenre } from "@/store/comics/type";
import axios from "axios";
import * as data from "@/assets/share_file/page.json";
const state: InterComics = reactive({
comicDatas: [] as InterComicsData[],
genreDatas: [] as InterGenre[],
pageLimit: 0 as number,
});
const actions = {
getComicDatas() {
// set root comic data
axios
.get(process.env.VUE_APP_SERVER + "getHanmanDatas")
.then((res: any) => {
let dataArrary: any[] = res.data;
dataArrary.forEach(function (item) {
item.genreDatas = [];
});
state.comicDatas = dataArrary;
})
.catch((err: any) => {
console.error(err);
});
axios
.get(process.env.VUE_APP_SERVER + "getGenreDatas")
.then((res: any) => {
let dataArrary: InterGenre[] = res.data;
state.genreDatas = dataArrary;
})
.catch((err: any) => {
console.error(err);
});
state.pageLimit = data.rootLimit;
},
};
export default { state, actions };
Vuex:
以前vuex在set/get data的時候必須要依靠dipatch傳字串進去,像這樣
import store from "@/store";
store.dispatch("rootComics/getRootComics", route.params.rootComics_id);
缺點是,在Coding時期時就失去了ts所帶來的優勢,他無法抓取到你寫的method,如果你namespace沒有命名甚至會直達頂樓到你最上層的,其實使用起來code變得很繁雜,也不直觀
Vue3-Reactive:
import rootComicsStore from "@/store/rootComics/storeRootComics"
rootComicsStore.actions.getRootComics(1111);
自從這樣寫之後,我的store減少了一大半file,也更簡略了,精神也變好了,記憶力也變強了(誤)
小結:
如果你問我vue3新的撰寫方法能不能取代掉vuex,我覺得是可以的,但前提是你已經能去定義你管理資料的結構,或是可以仿造vuex的結構,我會很推薦捨棄掉vuex的套件,自己定義管理資料的方法,如果未來上遇到缺點會再跟大家講的
留言
張貼留言