Vuex
全局 統(tǒng)一 單一
Vuex 是一個(gè)專為 Vue.js 應(yīng)用程序開發(fā)的狀態(tài)管理模式仰担。它采用集中式存儲(chǔ)管理應(yīng)用的所有組件的狀態(tài)摔蓝,并以相應(yīng)的規(guī)則保證狀態(tài)以一種可預(yù)測(cè)的方式發(fā)生變化愉耙。Vuex 也集成到 Vue 的官方調(diào)試工具 devtools extension,提供了諸如零配置的 time-travel 調(diào)試绘盟、狀態(tài)快照導(dǎo)入導(dǎo)出等高級(jí)調(diào)試功能悯仙。
-
解決問題
1.數(shù)據(jù)跨組件共享
2.防止數(shù)據(jù)意外修改
3.調(diào)試,測(cè)試
1.安裝
npm i vuex -S
2.引用
1.引入
import Vuex from 'vuex'
2.將 vuex
掛載到 vue 上
Vue.use(Vuex)
3.聲明 store 對(duì)象
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="javascript" cid="n63" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-size: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-top-left-radius: 3px; border-top-right-radius: 3px; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; background-position: inherit inherit; background-repeat: inherit inherit;">? const store = new Vuex.Store({
? strict: process.env.NODE_ENV!='production', //嚴(yán)格模式,防止直接修改 state .開發(fā)模式為 true, 生成模式為 false
state:{a:12,b:5}, //核心:數(shù)據(jù)
mutations:{},
actions:{},
getters:{}, //讀取數(shù)據(jù)
moudles:{}, //將 state 拆分成模塊
? })</pre>
<pre mdtype="fences" cid="n81" lang="javascript" class="md-fences md-end-block ty-contain-cm modeLoaded" spellcheck="false" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-size: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-top-left-radius: 3px; border-top-right-radius: 3px; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; background-position: inherit inherit; background-repeat: inherit inherit;">mutations:{
add(state,n){
state.a+n
}
}
actions:{
add(context,n){
context.commit('add'.n)
}
}
?
$store.state
$store.commit('mutation',payload);
$store.dispatch('action_name',payload);
?
mutation(state,arg){
state.a++
state.b+='arg'
}
?
action(contenxt,arg){
context.commit('mutation',arg)
}</pre>
4.使用