Vuex-的一般操作

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>

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

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理