前面兩篇我們已經大約了解了 Vuex 的運作模式,所以現在讓我們來用個簡單的例子實際運用看看吧!
Storestore,來控制 LOADING 狀態。export default new Vuex.Store({
state: {
isLoading: false
},
actions: {
updateLoading (context, status) {
context.commit('LOADING', status)
}
},
mutations: {
LOADING (state, status) {
state.isLoading = status
}
}
})
state 中放置一筆名為 isLoading 的資料mutations 中設立 LOADING 方法,以修改 state.isLoading 資料狀態actions 中設立 updateLoading 方法,以觸發 mutations 中的 LOADING 方法現在我們的 store 資料與方法都建立好了,那要如何在 Vue 元件中互動呢?
Vue 元件互動<template>
<div id="app">
<button @click="updateLoading">click</button>
<h2 v-if="isLoading">isLoading</h2>
</div>
</template>
<script>
export default {
name: 'app',
methods: {
updateLoading () {
this.$store.dispatch('updateLoading', true)
}
},
computed: {
isLoading () {
return this.$store.state.isLoading
}
}
}
</script>
methods 中設立 updateLoading 方法,並使用 this.$store.dispatch 方法,觸發在 store 中actions 的 updateLoading 方法,並傳入值為 true。computed 中設立 isLoading 方法,並使用 this.$store.state.isLoading 得到位於 store 中state 的 isLoading 值。其實在使用 Vuex 有一個重點,就是所有的資料修改都必須透過 mutation,為了預防我們違背了此原則,Vuxe 有提供嚴格模式來協助我們檢查,只要沒有符合原則就會跳錯。
而嚴格模式使用上也非常簡單哦!
const store = new Vuex.Store({
// ...
strict: true
})
const store = new Vuex.Store({
// ...
strict: process.env.NODE_ENV !== 'production'
})
這樣就只會在開發環境使用嚴格模式囉!