vuex經常讓我這樣的初學者摸不着頭腦,剛學完vuex的我想用下面幾個簡單通俗的栗子來進行小小的分享vue
Vuex 是一個專爲 Vue.js應用程序開發的狀態管理模式。它採用集中式存儲管理應用的全部組件的狀態,並以相應的規則保證狀態以一種可預測的方式發生變化。(vuex是以插件的方式存在的)
複製代碼
並非全部的項目都適合使用vuex,vuex通常適用於大型項目。在進行大型項目開發的時候,經常會碰到多個組件須要用到同一個狀態,這個時候,vuex就能派上用場,它能把組件的共享狀態抽取出來,當作一個全局單例模式進行管理。這樣無論你在何處改變狀態,都會通知使用該狀態的組件作出相應修改。
複製代碼
* 安裝 ---- `npm install vuex --save`
* 引入---- 以插件的方式引入,在src目錄下建立一個store.js文件並在其中引入
```
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
```
複製代碼
爲了更加通俗易懂地理解,引入公司的概念來闡述這四大核心
複製代碼
state ---- 惟一一個數據源,vuex的總倉庫,存儲數據 (至關於公司的CEO,掌管這公司總資產)vuex
mutations ---- 用於修改state的數據狀態,而且只能在mutations中修改state的數據 狀態(至關於公司的財務部門,擁有修改state的權力)npm
actions ---- 解決異步改變共享數據(至關於工做部門,向財務部門提交修改state的請求)bash
getters ---- 對state 裏面的數據二次處理(對數據進行過濾相似filter的做用)異步
下圖是這幾個狀態之間的關係圖:ide
一. 在store.js中定義好如下對象
複製代碼
const state = {
showSidebar: true,
}
複製代碼
const mutations = {
sidebar(state, status) {
state.showSidebar = status
}
}
複製代碼
const actions = {
setShowSidebar ({commit}, status) {
commit(sidebar, status)
}
}
複製代碼
const getters = {
showSidebar: state => state.showSidebar
}
複製代碼
最後再拋出這四個對象函數
export default {
state,
mutations,
actions,
getters
}
複製代碼
二. 調用store.js中的state的值學習
<template>
<div class="sidebar" :class="{showSidebar: showSidebar}" @click="_hidebar">
</div>
</template>
複製代碼
import { mapGetters } from 'vuex'
export default {
computed: {
...mapGetters([
'showSidebar'
])
}
}
複製代碼
methods: {
_hidebar () {
this.$store.dispatch('setShowSidebar', false)
}
}
複製代碼
...mapMutations ({}) 獲取mutations中的 sidebar 方法 ,並取名叫sidebar,第3點中的 _hidebar () {this.$store.dispatch('setShowSidebar', false)}
就能夠改寫爲 _hide () {this.sidebar(false)}
ui
...mapActions ([]) 獲取actions中的setShowSidebar 方法,與this.$store.dispatch('setShowSidebar')的做用同樣。this
**小提示:mapMutations中用{} mapActions中用[] **
<script>
import { mapGetters,mapMutations,mapActions } from "vuex"
export default {
computed: {
...mapGetters([
'showSidebar'
])
},
methods: {
...mapMutations({
sidebar: 'sidebar'
}),
...mapActions([
'setShowSidebar'
])
}
}
</script>
複製代碼
以上是來自一隻vue學習ing的大胖狗的分享,栗子是簡單通俗的,如有不合理的地方請大佬們輕噴。😘
複製代碼