Vuex 的通常操做

npm i vuex 下载

App.vue

<template>
<div id="app">vue

<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>vuex

<script>
export default {
name: 'App',
data(){npm

return {
}

},
computed:{
evenOrOdd(){app

return this.$store.getters.evenOrOdd

}
},
methods:{async

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>this

</style>spa

store.js

// Vuex的核心管理对象模块
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
//状态对象
const state ={eslint

// 初始状态
count: 0

}
//包含多个更新state函数的对象
const mutations ={
INCREMENT(state){
state.count++
},
DECREMENT(state) {code

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/>'})

相关文章
相关标签/搜索