«

vue 使用vuex

emer 发布于 2017-8-14 15:45   2747 次阅读     


app.vue:


<template>
  <div id="app">
    <input type="button" value="增加" @click="add">
    <h1>{{count}}</h1>
  </div>
</template>

<script>
import {mapGetters,mapActions} from "vuex"
export default {
  name: 'app',
 computed:mapGetters(["count"]),
 methods:mapActions(["add"])

}
</script>

main.js:



import Vue from 'vue'
import App from './App.vue'
import store from "./stores"
new Vue({
  el: '#app',
  store,
  render: h => h(App)
})
store下面的文件夹内:
type.js:

export const ADD ="ADD";

action.js:

import * as types from "./types"
const actions={
    add:({commit})=>{
        commit(types.ADD)
    }
}
export default{
    actions
}
mutations.js:

import {ADD} from "./types"
import getters from "./getters"
const state={
    count:0
}
const mutations={
    [ADD](state){
        state.count++
    }
}
export default {
    state,
    mutations,
    getters
}
getter.js:

export default{
    count:(state)=>{
        return state.count
    }
}

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
    }

})


要点:
在main里面一定要导入store