«
Vuex+Vue Router

时间:2022-3   


路由配置

import App from '../App'

export default [{
    path: '/',
    component: App,
    children: [{
        path: '',
        component: r => require.ensure([], () => r(require('../page/home')), 'home')
    }, {
        path: '/item',
        component: r => require.ensure([], () => r(require('../page/item')), 'item')
    }, {
        path: '/score',
        component: r => require.ensure([], () => r(require('../page/score')), 'score')
    }]
}]

配置actions

import ajax from '../config/ajax'

export default {
    addNum({ commit, state }, id) {
        //点击下一题,记录答案id,判断是否是最后一题,如果不是则跳转下一题
        commit('REMBER_ANSWER', id);
        if (state.itemNum < state.itemDetail.length) {
            commit('ADD_ITEMNUM', 1);
        }
    },
    //初始化信息
    initializeData({ commit }) {
        commit('INITIALIZE_DATA');
    }
}

mutations

const ADD_ITEMNUM = 'ADD_ITEMNUM'
const REMBER_ANSWER = 'REMBER_ANSWER'
const REMBER_TIME = 'REMBER_TIME'
const INITIALIZE_DATA = 'INITIALIZE_DATA'
export default {
    //点击进入下一题
    [ADD_ITEMNUM](state, payload) {
        state.itemNum += payload.num;
    },
    //记录答案
    [REMBER_ANSWER](state, payload) {
        state.answerid[state.itemNum] = payload.id;
    },
    /*
    记录做题时间
     */
    [REMBER_TIME](state) {
        state.timer = setInterval(() => {
            state.allTime++;
        }, 1000)
    },
    /*
    初始化信息,
     */
    [INITIALIZE_DATA](state) {
        state.itemNum = 1;
        state.allTime = 0;
    },
}

创建store

import Vue from 'vue'
import Vuex from 'vuex'
import mutations from './mutations'
import actions from './action'

Vue.use(Vuex)

const state = {
    level: '第一周',
    itemNum: 1,
    allTime: 0,
    timer: '',
    itemDetail: [],
    answerid: {}
}

export default new Vuex.Store({
    state,
    actions,
    mutations
})

创建vue实例

import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './router/router'
import store from './store/'

Vue.use(VueRouter)
const router = new VueRouter({
    routes
})

new Vue({
    router,
    store,
}).$mount('#app')