npm i vuex 下载
App.vue
<template>
<div id=”app”>
<p>click{{$store.state.count}} times, count is {{evenOrOdd}}</p>
<button @click="increment">+</button>
<button @click="decrement">-</button>
<button @click="incrementIfOdd">increment if odd</button>
<button @click="incrementAsync">increment if async</button>
</div>
</template>
<script>
export default {
name: ‘App’,
data(){
return {
}
},
computed:{
evenOrOdd(){
return this.$store.getters.evenOrOdd
}
},
methods:{
increment(){
// 通知Vuex去增加
this.$store.dispatch('increment') /* 触发store中对应的action调用 */
},
decrement(){
this.$store.dispatch('decrement')
},
// 如果是奇数才增加以
incrementIfOdd(){
this.$store.dispatch('incrementIfOdd')
},
// 过1s才增加
incrementAsync(){
this.$store.dispatch('incrementAsync')
},
}
}
</script>
<style>
</style>
App.vue另一种赞的写法
<template>
<div id=”app”>
<p>click{{count}} times, count is {{evenOrOdd}}</p>
<button @click="increment">+</button>
<button @click="decrement">-</button>
<button @click="incrementIfOdd">increment if odd</button>
<button @click="incrementAsync">increment if async</button>
</div>
</template>
<script>
import {mapState,mapActions,mapGetters} from ‘vuex’
export default {
name: ‘App’,
data(){
return {
}
},
computed:{
...mapState(['count']), //mapState()返回值:{count(){return this.$store.state['count']}}
...mapGetters(['evenOrOdd'])//mapGetters()返回值:{evenOrOdd(){return this.$store.getters['evenOrOdd']}}
},
methods:{
...mapActions(['increment','decrement','incrementIfOdd','incrementAsync'])
}
}
</script>
<style>
</style>
store.js
// Vuex的核心管理对象模块
import Vue from ‘vue’
import Vuex from ‘vuex’
Vue.use(Vuex)
//状态对象
const state ={
// 初始状态
count: 0
}
//包含多个更新state函数的对象
const mutations ={
INCREMENT(state){
state.count++
},
DECREMENT(state) {
state.count--
}
}
const actions = { //包含多个对应事件回调函数的对象
// 增加的action
increment({commit}) {
commit(‘INCREMENT’)
},
// 减少的action
decrement({commit}) {
commit('DECREMENT')
},
incrementIfOdd({commit,state}) {
// 不需要调用, 只需要读取属性值
if (state.count % 2 == 1) {
commit('INCREMENT')
}
},
incrementAsync({commit}) {
setTimeout(() => {
commit('INCREMENT')
}, 1000)
},
}
//包含多个getter计算属性的对象
const getters ={
evenOrOdd(state) {
return state.count % 2 == 0 ? ‘偶数’ : ‘奇数’;
},
}
export default new Vuex.Store({
state, //状态对象
mutations, //包含多个更新state函数的对象
actions, //包含多个对应事件回调函数的对象
getters //包含多个getter计算属性的对象
})
main.js引入
import Vue from ‘vue’
import App from ‘./App’
import store from ‘./store’
Vue.config.productionTip = false
/ eslint-disable no-new /
new Vue({
el: ‘#app’,
store,
components: { App },
template: ‘<App/>’
})