http://pan.baidu.com/s/1hrJfpli demo下載地址javascript
在一些項目中有不少數據狀態之間要實現數據共享狀態共享,例如購物車的數據、用戶的登陸狀態等等。vue父元素是能夠經過props向子元素傳遞參數,子元素也能夠通用smit向父元素傳遞參數。可是像購物車這種在項目中多個位置的引用時就會變得很麻煩。例如項目中使用了三個購物車的組件,那麼當其中一個組件的值發生改變時,就要經過自身告訴父組件個人值發生改變了,而後父組件在通知其餘兩個購物車組件值發生改變了,須要進行同步,這樣就會變得很麻煩。而vue-v就能夠幫助咱們解決這個繁瑣的問題。vue
npm install vuex java
項目需求:實現購物車商品增長和減小,並計算出商品的總價。ajax
準備工做vuex
import Vuex from 'vuex'
Vue.use(Vuex)
state:保存的是原始數據,能夠理解爲須要共享的數據或狀態,npm
getters:能夠理解爲是staore的計算屬性,能夠實現就store的計算,可是不能更改。例如你想知道兩個值相加、相乘。都是很是不錯的選擇。服務器
mutations:mutations中的方法能夠對state中的數據進行改變。函數
action:action中的方法能夠調用mutations中的方法,但不可修改state中的原始數據。action中的函數可使用ajax的技術對服務器進行數據交互。而且能夠在回調中使用commit調用mutations中的方法,例如經過context.commit('increment', price)increment是須要調用mutations中的方法名,price是須要傳入的參數。 mutations中的方法再去更改state的原始數據。this
let store = new Vuex.Store({ state: { totalPrice: 0 }, getters: { getTotal (state) { return state.totalPrice*2 } }, mutations: { increment (state, price) { state.totalPrice += price }, decrement (state, price) { state.totalPrice -= price } }, actions: { increase (context, price) { context.commit('increment', price) } } })
在組件內部使用 this.$store.state.屬性名便可。spa
實例代碼:
computed: { totalPrice () { return this.$store.state.totalPrice }
computed: { getTotal () { return this.$store.getters.getTotal } }
methods: { addOne () { this.$store.commit('increment', this.price) }, minusOne () { this.$store.commit('decrement', this.price) } }
methods: { addOne () { this.$store.dispatch('increase', this.price) } }