該節教程代碼可經過npm start運行devServer,在http://localhost:8080/查看效果css
Vuex 是一個專爲 Vue.js 應用程序開發的狀態管理模式。它採用集中式存儲管理應用的全部組件的狀態,並以相應的規則保證狀態以一種可預測的方式發生變化。html
Vuex具備如下特色:vue
Vuex解決了哪些問題:git
代碼示例:/lesson20/src/main.jsgithub
先使用vue-cli建立一個項目,以後使用npm install vuex --save安裝Vuex,就能夠在/src/main.js中配置Vuex:vuex
// 1. vuex-引入
import Vuex from 'vuex'
// vue-cli自帶的編譯配置
Vue.config.productionTip = false
// 1. vuex-在Vue中使用Vuex,讓Vuex中的操做掛載到Vue中。
Vue.use(Vuex)
// 3. vuex-聲明store對象
const store = new Vuex.Store({
strict: process.env.NODE_ENV !== 'production', // 嚴格模式:防止直接修改state,只能用Mutations操做,因爲strict模式是經過對象深度匹配進行,生產模式打開會嚴重影響性能。
state: {a: 12, b: 5}, // 核心:數據
mutations: { // 定義Mutations
},
actions: { // 定義actions
},
getters: {}, // 相似於computed
modules: {} // 將store拆分紅多個命名空間,分開使用。
})
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store, // 將store掛載到Vue實例中。
components: { App },
template: '<App/>'
})
複製代碼
代碼示例:/src/components/Index.vuevue-cli
在Index.vue中能夠經過$store.state.a讀取到已定義的a的值。npm
<template>
<div>
<!-- 讀取Vuex的state -->
a: {{$store.state.a}}
<Cmp1/>
<Table :fields="fields" :datas="datas" :parent="this"/>
</div>
</template>
複製代碼
接下來實如今Cmp1.vue組件中,點擊按鈕後修改state中的a的值。bash
代碼示例:/src/components/Cmp1.vueapp
<template lang="html">
<div class="">
<input type="button" value="+5" @click="fn()">
</div>
</template>
<script>
export default {
name: 'cmp1',
methods: {
fn(){
// this.$store.state.a+=5; // 在嚴格模式下,直接修改state能夠成功,但會報錯
// this.$store.commit('add', 5); // 直接觸發一個Mutation其實也可行,且不會報錯,但這其實違背了Vuex設計的初衷。
this.$store.dispatch('add', 5); // 觸發一個action,實現數據修改。
}
}
}
</script>
<style lang="css" scoped>
</style>
複製代碼
在main.js中定義Actions和Mutations。
代碼示例:/lesson20/src/main.js
const store = new Vuex.Store({
strict: process.env.NODE_ENV !== 'production', // 嚴格模式:防止直接修改state,只能用Mutations操做,因爲strict模式是經過對象深度匹配進行,生產模式打開會嚴重影響性能。
state: {a: 12, b: 5}, // 核心:數據
mutations: { // 定義Mutations,經過action觸發並更新state,Vue Devtool能夠監聽到數據的修改狀況。
add (state, n) { // 第一個參數爲舊state,第二個參數爲action中commit傳入的參數。
state.a += n
}
},
actions: { // 定義actions,actions被觸發後,將數據提交給Mutations進行處理並更新state。
add ({ commit }, n) { // 第一個參數爲context對象,它不是store自己,能夠經過context.commit提交一個Mutation。第二個參數爲用於更新state的參數。
commit('add', n)
}
},
getters: {}, // 相似於computed
modules: {} // 將store拆分紅多個命名空間,分開使用。
})
複製代碼