Lala Code

Lala 的前端大補帖,歡迎一起鑽研前端技術😊

0%

在 Nuxt 管理 vuex 狀態

Imgur

要在 Nuxt 使用 vuex ,直接在 store 新增 index.js,並用函式的方式回傳 state,加入 actions、mutations、getters,即可直接使用。

Nuxt 操作 vuex

store/index.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// state
export const state = () => ({
idx: 0,
});

// actions
export const actions = {
handAddCount({ commit }) {
commit('addCount');
},
};

// mutations
export const mutations = {
addCount(state) {
state.idx++;
},
};

// getters
export const getters = {
getIdx(state) {
return `count: ${state.idx}`;
},
};

index.vue

1
2
<h1>{{ count }}</h1>
<button type="button" @click="clickBtn">ADD</button>
1
2
3
4
5
6
7
8
9
10
11
12
export default {
methods: {
clickBtn() {
this.$store.dispatch('handAddCount');
},
},
computed: {
count() {
return this.$store.getters.getIdx;
},
},
};

asyncData 取得 store 資料

想在 asyncData 取得 store,可從 context 去抓取

1
<h1>{{ asyncCount }}</h1>
1
2
3
4
5
export default {
asyncData(context) {
return { asyncCount: context.app.store.state.idx };
},
};

拆分 module

寫在同一支的 module

在 store 新增 User 資料夾,等於直接創建了一個 User 的 module

store/User/index.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// state
export const state = () => ({
name: 'bobee',
});

// actions
export const actions = {
log() {
console.log('123');
},
};

// mutations
export const mutations = {};

// getters
export const getters = {};

直接 this.$store.state.User 就可以取得到 User 裡的資料

index.vue

1
2
3
4
mounted() {
console.log(this.$store.state.User.name);
console.log(this.$store.dispatch("User/log"));
},

拆分四支檔案的 module

也可以把 state、actions、mutations、getters 拆分成四支檔案,取得資料的方法也是同樣的

store/User/state.js

1
2
3
export default () => ({
title: 'nuxt',
});

store/User/actions.js

1
export default {};

store/User/mutations.js

1
export default {};

store/User/getters.js

1
export default {};

Plugins 注入 Vuex

已載入全域的 plugins,只有在 nuxt 上可以使用,vuex 上沒辦法調用,
所以需要將套件的方法注入到 Vuex 裡面,假如我們已經在專案上安裝好了 vue-notification 套件,在layout的地方注入方法

layout/defalut.vue

1
2
3
created(){
this.$store.$notify = this.$notify
}

這麼一來,就可以在 store 使用 this.$notify 了!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
export const actions = {
handAddCount({ commit }) {
commit("AddCount");
},
async handApiData({ commit }) {
try {
const res = await apiGetPhotoData();
commit("AddCount", { data: res.data });
} catch (error) {
// 錯誤處理
console.log("錯誤處理:", error);
this.$notify({
group: "foo",
title: "API資料錯誤",
type: "error",
text: error
});
}
}
};

筆記來源: 2021 Vue3 專業職人 | 進階篇



Hey!想學習更多前端知識嗎?

最近 Lala 開了前端課程 👉【實地掌握RWD - 12小時新手實戰班】👈
無論您是 0 基礎新手,又或是想學 RWD 的初學者,
我們將帶你從零開始,深入了解並掌握 RWD 響應式網頁設計的核心技術,快來一起看看吧 😊



🚀線上課程分享

線上課程可以加速學習的時間,省去了不少看文件的時間XD,以下是我推薦的一些課程
想學習更多關於前後端的線上課程,可以參考看看。

Hahow

Hahow 有各式各樣類型的課程,而且是無限次數觀看,對學生或上班族而言,不用擔心被時間綁住



六角學院

如果你是初學者,非常推薦六角學院哦!
剛開始轉職也是上了六角的課,非常的淺顯易懂,最重要的是,隨時還有線上的助教幫你解決問題!


Udemy

Udemy 裡的課程非常的多,品質普遍不錯,且價格都滿實惠的,CP值很高!
也是很多工程師推薦的線上課程網站。
❤️