1 //store.js 2 /** 3 * vuex配置 4 */ 5 6 import Vue from 'vue' 7 import Vuex from 'vuex' 8 9 Vue.use(Vuex); 10 11 //定义属性(数据) 12 var state={ 13 count:6 14 } 15 16 //定义getters 17 var getters={ 18 count(state){ 19 return state.count; 20 }, 21 isEvenOrOdd(state){ 22 return state.count%2==0?'偶数':'奇数'; 23 } 24 } 25 26 //定义actions,要执行的操作,如流程判断、异步请求等 27 const actions = { 28 increment(context){//包含:commit、dispatch、state 29 console.log(context); 30 // context.commmit() 31 }, 32 // increment({commit,state}){ 33 // commit('increment'); //提交一个名为increment的变化,名称可自定义,可以认为是类型名 34 // }, 35 decrement({commit,state}){ 36 if(state.count>10){ 37 commit('decrement'); 38 } 39 }, 40 incrementAsync({commit,state}){ 41 //异步操作 42 var p=new Promise((resolve,reject) => { 43 setTimeout(() => { 44 resolve(); 45 },3000); 46 }); 47 48 p.then(() => { 49 commit('increment'); 50 }).catch(() => { 51 console.log('异步操作'); 52 }); 53 } 54 } 55 56 //定义mutations,处理状态(数据)的改变 57 const mutations={ 58 increment(state){ 59 state.count++; 60 }, 61 decrement(state){ 62 state.count--; 63 } 64 } 65 66 //创建store对象 67 const store=new Vuex.Store({ 68 state, 69 getters, 70 actions, 71 mutations 72 }) 73 74 //导出store对象 75 export default store;
1 //main.js 2 import Vue from 'vue' 3 import App from './App.vue' 4 5 import store from './store.js' //导入store对象 6 7 new Vue({ 8 store, //配置store选项,指定为store对象,会自动将store对象注入到所有子组件中,在子组件中通过this.$store访问该store对象 9 el: '#app', 10 render: h => h(App) 11 })
1 //App.vue 2 <template> 3 <div id="app"> 4 5 <button @click="increment">增加</button> 6 <button @click="decrement">减小</button> 7 <button @click="incrementAsync">增加</button> 8 <p>当前数字为:{{count}}</p> 9 <p>{{isEvenOrOdd}}</p> 10 11 </div> 12 </template> 13 14 <script> 15 import {mapState,mapGetters,mapActions} from 'vuex' 16 17 export default { 18 name: 'app', 19 data () { 20 return { 21 msg: 'Welcome to Your Vue.js App' 22 } 23 }, 24 //方式1:通过this.$store访问 25 /*computed:{ 26 count(){ 27 return this.$store.state.count; 28 } 29 }*/ 30 /*computed:mapState([ 31 'count' 32 ]),*/ 33 computed:mapGetters([ 34 'count', 35 'isEvenOrOdd' 36 ]), 37 methods:mapActions([ 38 'increment', 39 'decrement', 40 'incrementAsync' 41 ]) 42 } 43 </script> 44 45 <style> 46 #app { 47 font-family: 'Avenir', Helvetica, Arial, sans-serif; 48 -webkit-font-smoothing: antialiased; 49 -moz-osx-font-smoothing: grayscale; 50 text-align: center; 51 color: #2c3e50; 52 margin-top: 60px; 53 } 54 55 h1, h2 { 56 font-weight: normal; 57 } 58 59 ul { 60 list-style-type: none; 61 padding: 0; 62 } 63 64 li { 65 display: inline-block; 66 margin: 0 10px; 67 } 68 69 a { 70 color: #42b983; 71 } 72 </style>