store

//action.js
import * as types from './types'
console.log(types)
export default {
  increment:({commit})=>{
    commit(types.INCREMENT)
  },
  decrement({commit}){
    commit(types.DECREMENT)
  },
  clickOdd({commit,state}){
    if (state.mutations.count%2==0) {
      commit(types.INCREMENT)
    }
  },
  clickAsync({commit}){
    new Promise((resove)=>{
      setTimeout(()=>{
        commit(types.INCREMENT)
        resolve()
      },1000)
    })
  }
}

//getters.js
export default {
  count:(state)=>state.count,
  odd:(state)=>state.count%2==0?"偶数":"奇数"
}

//index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

import  mutations from './mutations'
import actions from './actions'

export default new Vuex.Store({
  modules:{
    mutations
  },

  actions

})

//mutation.js
import {
  INCREMENT,
  DECREMENT
} from './types'
import getters from './getters'
const state={
  count:10
}
const mutations={
  [INCREMENT](state){
    state.count++
  },
  [DECREMENT](state){
    state.count--
  }
}
export default{
  state,
  mutations,
  getters
}

//types.js
export const INCREMENT='INCREMENT' ;
export const DECREMENT='DECREMENT' ;

//app.vue
<template>
  <div id="app">
    <h1>welcome to vuex</h1>
    <input type="button" name="" value="点击增加" @click='increment'>
    <input type="button" name="" value="点击减少" @click="decrement">
    <input type="button" name="" value="只有偶数才能点击+" @click="clickOdd">
    <input type="button" name="" value="异步增加" @click="clickAsync">
    <div class="">
      现在的数字是:{{count}},他是{{odd}}
    </div>
  </div>

</template>

<script>
import {mapGetters,mapActions} from 'vuex'
export default {
  computed:mapGetters([
    'count',
    'odd'
  ]),
  methods:mapActions([
    'increment',
    'decrement',
    "clickOdd",
    "clickAsync"
  ])
}
</script>


<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}

h1, h2 {
  font-weight: normal;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  display: inline-block;
  margin: 0 10px;
}

a {
  color: #42b983;
}
</style>
//main.js
import Vue from 'vue'
import App from './App.vue'
import store from './store/index'

new Vue({
  store,
  el: '#app',
  render: h => h(App)
})

You can change the world with your heart,even a lot of changes sometimes unless you won't geiv up....
原文地址:https://www.cnblogs.com/xiongwei2017/p/6616445.html