下面我將以一個簡單的計數器做爲例子來使用vuex。vue
父子組件:直接經過Props屬性
兄弟組件:跟組件APP.vue組件下面有A.vue和B.vue兩個子組件
複製代碼
A組件和B組件之間的通訊過程是這樣的:
A組件:老爸,幫我傳遞個消息給B組件。(這時候A.vue dispatch 一個事件給 APP.vue)
APP組件:就是幹(APP.vue 監聽A.vue的 dispatch事件,同時須要broadcast一個事件給B組件)
B組件:收到信息(經過on監聽App.vue組件的分發事件)
複製代碼
具體邏輯以下webpack
用戶在組件中的輸入操做觸發 action 調用;
Actions 經過分發 mutations 來修改 store 實例的狀態;
Store 實例的狀態變化反過來又經過 getters 被組件獲知。
複製代碼
- 3.1 首先經過命令行生成項目結構
$ vue init webpack vuex
$ cnpm install
安裝vuex(vuex會添加到dependencies中)
$ npm install vuex --save
複製代碼
- 3.2 將store相關的代碼分離出來
<template>
<div class="hello">
<p>{{count}}
<button @click="inc">+</button>
<button @click="dec">-</button>
</p>
</div>
</template>
<script>
export default {
data () {
return {
msg: 'Welcome to Your Vue.js App'
}
},
computed: {
count() {
return this.$store.state.count
}
},
methods: {
inc() {
this.$store.commit('inc')
},
dec() {
this.$store.commit('dec')
}
}
}
</script>
複製代碼
- 3.3 在main.js中引入store文件 main.js
import store from './store'
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
複製代碼
- 3.4 在HelloWorld.vue中使用store裏面的count變量 HelloWorld.vue
<template>
<div class="hello">
<p>{{count}}
<button @click="inc">+</button>
<button @click="dec">-</button>
</p>
</div>
</template>
<script>
export default {
computed: {
count() {
return this.$store.state.count
}
},
methods: {
inc() {
this.$store.commit('inc')
},
dec() {
this.$store.commit('dec')
}
}
}
</script>
複製代碼
完成到這一步 , 上述例子中的 this.$store.state.count 就能夠使用了。咱們就能夠實現計數的功能。web
main.jsvuex
import Vue from 'vue'
import App from './App'
import router from './router'
import vuex from 'vuex'
import store from './store'
Vue.use(vuex);
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
複製代碼
HelloWorld.vuenpm
<template>
<div class="hello">
<p>
Value: {{ count }}
<button @click="increment">+</button>
<button @click="decrement">-</button>
</p>
</div>
</template>
<script>
import {mapGetters, mapActions} from 'vuex'
export default {
created() {
console.log(this.$store)
},
computed: mapGetters([
'count'
]),
methods: mapActions([
'increment',
'decrement'
])
}
</script>
複製代碼
actions.jsbash
export const increment = ({ commit }) => commit('increment')
export const decrement = ({ commit }) => commit('decrement')
複製代碼
mutations.jsapp
export const increment = state => {
state.count++
}
export const decrement = state => {
state.count--
}
複製代碼
getters.js組件化
export const count = state => state.count
複製代碼
index.jsui
import Vue from 'vue'
import Vuex from 'vuex'
import * as getters from './getters'
import * as actions from './action'
import * as mutations from './mutataions'
Vue.use(Vuex);
const state = {
count: 0
}
export default new Vuex.Store({
state,
getters,
actions,
mutations
})
複製代碼