项目代码结构↓
src内容↓
store内容↓
理解思路: component中的组件发送修改请求,由action.js处理请求,mutation修改请求,修改请求后state改变,从getter.js中可获取更新后的state中的数据。
state.js中为初始数据
const state={ count:0 }; export default state;
action.js中的内容
import * as types from './types'; const actions={ increment:({ commit,state },payload)=>{ // alert(payload); payload=payload||1; commit(types.INCREMENT,payload); }, decrement:({ commit,state })=>{ commit(types.DECREMENT); }, async:({ commit,state })=>{ setTimeout(()=>{//请求数据 commit(types.INCREMENT); },1000); }, odd:({ commit,state })=>{ if(state.count % 2 == 0){ commit(types.INCREMENT); } } }; export default actions;
mutation.js的内容
import { INCREMENT, DECREMENT } from './types'; const mutations={ [INCREMENT]:(state,payload)=>{ // alert(payload); payload=payload||1; state.count+=payload; }, [DECREMENT]:(state)=>{ state.count--; } }; export default mutations;
type.js的内容
export const INCREMENT='INCREMENT'; //加 描述 export const DECREMENT='DECREMENT'; //减 描述
getter.js的内容
const getters={ count:(state)=>{ return state.count; } }; export default getters;
在App.vue(或其他组件)中获取、修改state中的状态↓
<template> <div id="app"> <h1>vuex</h1> <input type="button" value="+" @click="increment(2)"> <input type="button" value="-" @click="decrement"> <input type="button" value="异步+" @click="async"> <input type="button" value="偶数+" @click="odd"> <br/> 越过getters向state拿:{{$store.state.count}} <br/> {{count}}/{{count%2==0?'双数':'单数'}} <br/> <input type="button" value="修改私有数据" @click="check"> <br/> {{n}} </div> </template> <script> import {mapActions,mapGetters} from 'vuex'; export default { name: 'app', data () { return { n:0 } }, methods:{ // 私有方法和 请求并存 check(){ this.n='bmw'; }, ...mapActions( ['increment','decrement','async','odd'] ) }, computed:mapGetters( ['count'] ), mounted(){ //代码里面直接发请求 actions // this.$store.dispatch('increment',121); //代码里面直接发请求 mutations // this.$store.commit('INCREMENT',['apple','banana','orange','西游记']); } } </script> <style> </style>