前面两篇我们已经大约了解了 Vuex 的运作模式,所以现在让我们来用个简单的例子实际运用看看吧!
Store
store
,来控制 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'
})
这样就只会在开发环境使用严格模式罗!
<<: Day 0x8 UVa10193 All You Need Is Love
>>: Day5 - 新鲜人提升开发效率的方法(扩充套件篇)
注:发文日和截图的日期不一定是同一天,所以价格计算上和当日不同,是很正常的。 买进 大同(2371)...
同时开启多个浏览器 有时候可能需要多个浏览器来进行测试, 譬如说用多个浏览器来测试WebSocket...
资料系结的主题讲了好几天,那麽,就来小试身手一下,透过一个简单的实作,把这几天所学到的观念,试着运用...
学习进度 第一周的练习小考与检讨 课後练习与习题检讨 继承、多型与介面 继承(extends)原则与...
前言 确定画面都可以正确呈现与转换後,我们来正式实作登入的画面。 Nav LoginViewCont...