效果图:
vue的app.vue
<template>
<div>
<p>click {{count}} times,count is {{evenOrOdd}}</p>
<button @click="increment">+</button>
<button @click="decrement">-</button>
<button @click="incrementIfOdd">odd</button>
<button @click="incrementasync">async</button>
</div>
</template> <script>
export default {
data(){
return{
count:0
}
}, computed:{
evenOrOdd(){
return this.count%2===0 ? '偶数':"奇数"
}
},
methods:{
increment(){
let count=this.count
this.count= count+1
},
decrement(){
let count=this.count
this.count= count-1
},
//如果是奇数才增加
incrementIfOdd(){
let count=this.count
if(count%2===1){
this.count= count+1
}
},
//过一秒才增加
incrementasync(){
setTimeout(()=>{
let count=this.count
this.count= count+1
},1000)
}
}
}
</script> <style> </style>
vuex的app.vue
<template>
<div>
<p>click {{$store.state.count}} times,count is {{evenOrOdd}}</p>
<button @click="increment">+</button>
<button @click="decrement">-</button>
<button @click="incrementIfOdd">odd</button>
<button @click="incrementasync">async</button>
</div>
</template> <script>
export default {
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')
},
//过一秒才增加
incrementasync(){
this.$store.dispatch('incrementasync')
}
}
}
</script> <style> </style>
vuex的store.js
//vuex的核心管理对象模块
import Vue from 'vue'
import Vuex from 'vuex' Vue.use(Vuex) //状态
const state = { //初始化状态
count:0
} //包含多个更新mutations函数的对象
const mutations = {
//增加的mutation
INCREMENT(state){
state.count++
},
//减少的mutation
DECREMENT(state){
state.count--
}
} //包含多个更新actions函数的对象
const actions = {
//增加action
increment({commit}){
commit("INCREMENT")
},
decrement({commit}){
commit("DECREMENT")
},
incrementIfOdd({commit,state}){
if(state.count%2===1){
commit("INCREMENT")
}
},
//异步的action
incrementasync({commit}){
setTimeout(()=>{
commit("INCREMENT")
},1000)
}
} //包含多个更新getters函数的对象
const getters = {
evenOrOdd(state){
return state.count%2===0 ? '偶数':"奇数"
}
}
export default new Vuex.Store({
state,//状态
mutations,//包含多个更新state函数的对象
actions,//对应多个对应事件回调函数的对象
getters // 包含多个getter计算属性函数的对象
})
vuex的main.js
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import store from './store' /* eslint-disable no-new */
new Vue({
el: '#app',
components: { App },
template: '<App/>',
store //所有的组件对象都多了一个$store
})