1.先看项目的目录结构
2.在main.js里需要引入store这个文件并挂在实例上
import store from './store/store' ............new Vue({el: '#app',router,store,template: '<App/>',components: { App } })
3.store.js里引入action.js和mutation.js文件
// 状态管理器
import Vue from 'vue'
import Vuex from 'vuex'
import actions from './action'
import mutations from './mutation'
Vue.use(Vuex)const store = new Vuex.Store({state : {author: 'Wise Wrong',amsg: '',},actions,mutations,getters:{author(state){console.log(state)return state.author}}
})
export default store
4.action.js
import * as types from './mutation_type'
export default{newAuthor({commit},bData){commit(types.NEWAUTHOR,bData);}
}
5.mutation.js
import * as types from './mutation_type'
export default{[types.NEWAUTHOR](state,msg){state.author=msg;}
}
6.mutation_type.js
export const SEND_A="SEND_A"
export const NEWAUTHOR="NEWAUTHOR"
7.head.vue
temple: <form class="navbar-form navbar-left"><div class="form-group"><input type="text" v-model="inputTxt" class="form-control" placeholder="通过input改变author"></div><button type="button" class="btn btn-default" @click="setAuthor">Submit</button></form>script:data () {return {inputTxt:""}},methods:{setAuthor: function () {this.$store.dispatch("newAuthor", this.inputTxt);}}
8.foot.vue
<p>Copyright © author:{{author}} - 2016 All rights reserved</p>import { mapGetters} from 'vuex' computed: {...mapGetters(['author'])}
9.效果