Vuex

2019-12-19  本文已影响0人  Mokingc

Vuex

全局 统一 单一

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。Vuex 也集成到 Vue 的官方调试工具 devtools extension,提供了诸如零配置的 time-travel 调试、状态快照导入导出等高级调试功能。

image.png

1.安装

npm i vuex -S

2.引用

1.引入

import Vuex from 'vuex'

2.将 vuex挂载到 vue 上

Vue.use(Vuex)

3.声明 store 对象

<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',              //严格模式,防止直接修改 state .开发模式为 true,  生成模式为 false
 state:{a:12,b:5},  //核心:数据
 mutations:{},
 actions:{}, 
 getters:{},        //读取数据
 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.使用

上一篇 下一篇

猜你喜欢

热点阅读