這段時間一直在用vue寫項目,vuex在項目中也會依葫蘆畫瓢使用,但是總有一種朦朦朧朧的感覺。於是決定徹底搞懂它。
看了一下午的官方文檔,以及資料,才發現vuex so easy!
作為一個圈子中的人,決定輸出一下文檔,如果你仔細看完這篇文章,保證你對vuex熟練掌握。
我把自己的代碼上傳到了github,大家有需要的可以拉下來:github
先說一下vuex到底是什么?
vuex 是一個專門為vue.js應用程序開發的狀態管理模式。
這個狀態我們可以理解為在data中的屬性,需要共享給其他組件使用的部分。
也就是說,是我們需要共享的data,使用vuex進行統一集中式的管理。
vuex中,有默認的五種基本的對象:
- state:存儲狀態(變量)
- getters:對數據獲取之前的再次編譯,可以理解為state的計算屬性。我們在組件中使用 $sotre.getters.fun()
- mutations:修改狀態,並且是同步的。在組件中使用$store.commit('',params)。這個和我們組件中的自定義事件類似。
- actions:異步操作。在組件中使用是$store.dispath('')
- modules:store的子模塊,為了開發大型項目,方便狀態管理而使用的。這里我們就不解釋了,用起來和上面的一樣。
下面我們正式開始,一步步使用vuex
1、首先創建一個vue-cli項目
執行下面的命令,創建一個app項目(這里也可以使用其他非webpack模板,以及非app名稱)
vue init webpack app
2、創建完成之后,我們進入文件夾下,並且運行項目
cd app/
npm run dev
接下來我們在src目錄下創建一個vuex文件夾
並在vuex文件夾下創建一個store.js文件
文件夾目錄長得是這個樣子
3、目前我們還沒有引入vuex,我們需要先下載vuex,並且引入它
在保證我們處於我們項目下,在命令行輸入下面命令,安裝vuex
npm install vuex --save
4、安裝成功之后,我們就可以在store.js中盡情玩耍我們的vuex了!
在store.js文件中,引入vuex並且使用vuex,這里注意我的變量名是大寫Vue和Vuex
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const state = { count: 0 } export default new Vuex.Store({ state })
接下來,在main.js中引入store
import Vue from 'vue' import App from './App' import router from './router' import store from './vuex/store' // 引入store Vue.config.productionTip = false /* eslint-disable no-new */ new Vue({ el: '#app', router, store, components: { App }, template: '<App/>' })
然我我們在任意一個組件中就可以使用我們定義的count屬性了。
這里我們在helloWorld中使用一下,去除helloworld.vue中不用的標簽
<template> <div class="hello"> <h3>{{$store.state.count}}</h3> </div> </template>
打開我們剛才運行項目的瀏覽器,可以看到已經使用成功了!
並且在vue開發工具中我們可以看到我們定義的變量count
到這一步,已經成功了一小半!vuex很簡單吧?
回想一下,我們只需要在下載安裝使用vuex,在我們定義的store.js中定義state對象,並且暴露出去。
在main.js中使用我們的store.js(這里是為了防止在各個組件中引用,因為main.js中,有我們的new Vue 實例啊!)
現在我們已經使用了vuex中的state,接下來我們如何操作這個值呢? 沒錯!用mutations和actions
我們繼續操作store.js文件
我們在sotre.js中定義mutations對象,該對象中有兩個方法,mutations里面的參數,第一個默認為state,接下來的為自定義參數。
我們在mutations中定義兩個方法,增加和減少,並且設置一個參數n,默認值為0,然后在Vuex.Store中使用它
/** * mutations 里面放置的是我們操作state對象屬性的方法 */ const mutations = { mutationsAddCount(state, n = 0) { return (state.count += n) }, mutationsReduceCount(state, n = 0) { return (state.count -= n) } } export default new Vuex.Store({ state, mutations })
然后我們在helloWorld.vue中,使用這個方法
還記得我們如何在組件中使用mutations嗎?就和自定義事件非常相似
<template> <div class="hello"> <h3>{{$store.state.count}}</h3> <div> <button @click="handleAddClick(10)">增加</button> <button @click="handleReduceClick(10)">減少</button> </div> </div> </template>
methods: { handleAddClick(n){ this.$store.commit('mutationsAddCount',n); }, handleReduceClick(n){ this.$store.commit('mutationsReduceCount',n); } }
來瀏覽器看一下效果如何!
我們可以看到每當觸發事件時,我們都可以在vue開發工具中看到我們觸發的mutations方法,以及參數
完美!
接下來就是actions,actions是異步操作
創建actions對象,並且使用
這里我在兩個方法中使用了兩個不同的參數,一個是context,它是一個和store對象具有相同對象屬性的參數。在第二個函數中,我是直接使用了這個對象的commit的方法。
憑大家喜好就行
const actions = { actionsAddCount(context, n = 0) { console.log(context) return context.commit('mutationsAddCount', n) }, actionsReduceCount({ commit }, n = 0) { return commit('mutationsReduceCount', n) } } export default new Vuex.Store({ state, mutations, actions })
在helloWorld.vue中
在methods中,增加兩個方法,使用dispath來觸發
<div>異步操作</div> <div> <button @click="handleActionsAdd(10)">異步增加</button> <button @click="handleActionsReduce(10)">異步減少</button> </div>
handleActionsAdd(n){ this.$store.dispatch('actionsAddCount',n) }, handleActionsReduce(n){ this.$store.dispatch('actionsReduceCount',n) }
進入瀏覽器看下效果如何!
最后就是getters
我們一般使用getters來獲取我們的state,因為它算是state的一個計算屬性
const getters = { getterCount(state, n = 0) { return (state.count += n) } } export default new Vuex.Store({ state, mutations, actions, getters })
<h4>{{count}}</h4>
const getters = { getterCount(state) { return (state.count += 10) } }
getters算是非常簡單的了。
到這里,如果全都看懂了,vuex你已經沒有壓力了。
但是vuex官方給了我們一個更簡單的方式來使用vuex, 也就是 {mapState, mapMutations, mapActions, mapGetters}
只要我們把上面基礎的搞懂,這些都不在話下,只是方面我們書寫罷了。
就這么簡單,這里我們用到了es6的擴展運算符。如果不熟悉的同學還是去看看阮一峰大神的《Es6標准入門》這本書,我是看完了,受益匪淺!
<script> import {mapState, mapMutations, mapActions, mapGetters} from 'vuex' export default { name: 'HelloWorld', data () { return { msg: 'Welcome to Your Vue.js App' } }, methods: { ...mapMutations({ handleAddClick: 'mutationsAddCount', handleReduceClick: 'mutationsReduceCount' }), ...mapActions({ handleActionsAdd: 'actionsAddCount', handleActionsReduce: 'actionsReduceCount' }) // handleAddClick(n){ // this.$store.commit('mutationsAddCount',n); // }, // handleReduceClick(n){ // this.$store.commit('mutationsReduceCount',n); // }, // handleActionsAdd(n){ // this.$store.dispatch('actionsAddCount',n) // }, // handleActionsReduce(n){ // this.$store.dispatch('actionsReduceCount',n) // } }, computed: { count(){ return this.$store.getters.getterCount } } } </script>
同理,getters和 state也可以使用 mapState,mapGetters
如果你更懶的話,我們可以使用數組,而非對象,或者es6里面的對象簡寫方式
就像這種
最后,如果大家發現有什么問題,或者錯誤的地方,歡迎留言交流。
分割線----------------------------------------------------------------------
看到后台一些小伙伴問我用的什么編輯器,我這里用的是vscode,然后把我自己的一些配置給貼上,喜歡的話可以粘貼復制一下。
最近的效果是這樣子的~~
字體用的是Fira Code 很好用的一種字體
{ "editor.fontFamily": "Fira Code", "editor.fontLigatures": true, "editor.cursorStyle": "block", "editor.fontSize": 16, "editor.lineHeight": 24, "editor.lineNumbers": "on", "editor.minimap.enabled": false, "editor.renderIndentGuides": false, "editor.rulers": [120], "workbench.colorTheme": "Andromeda", "workbench.iconTheme": "vscode-great-icons", "editor.detectIndentation": false, "editor.tabSize": 2, "editor.quickSuggestions": { "other": true, "comments": true, "strings": true }, "files.associations": { "*.cjson": "jsonc", "*.wxss": "css", "*.wxs": "javascript" }, "emmet.includeLanguages": { "wxml": "html" }, "minapp-vscode.disableAutoConfig": true, "window.zoomLevel": -1, "[vue]": { "editor.defaultFormatter": "octref.vetur" }, "todo-tree.defaultHighlight": { "type": "text", }, "todo-tree.customHighlight": { "TODO": { "icon": "check", "foreground": "#000", "background": "#cecb32", "iconColour": "#fffc43" }, "FIXME": { "icon": "alert", "foreground": "#fff", "background": "#ca4848", "iconColour": "#ff4343" } }, "todo-tree.highlights.customHighlight": { "TODO": { "icon": "check", "foreground": "#000", "background": "#cecb32", "iconColour": "#fffc43" }, "FIXME": { "icon": "alert", "foreground": "#fff", "background": "#ca4848", "iconColour": "#ff4343" } }, "todo-tree.highlights.defaultHighlight": { "type": "text" } }