學(xué)習(xí)一個(gè)框架有兩個(gè)階段最難,一個(gè)是初期的入門(mén)属桦,一個(gè)是后期的源碼閱讀熊痴。
雖然vue的官方文檔非常棒,在我讀完文檔之后還是會(huì)有一種感覺(jué)聂宾,知識(shí)點(diǎn)我都懂果善,然后呢?似乎大體知道該怎么利用vue全家桶去搭建一個(gè)項(xiàng)目系谐,但具體下筆又有點(diǎn)模糊巾陕。vue官方的腳手架并沒(méi)有將vue-router和vuex包括進(jìn)去,所以我們需要自己去配置它們纪他。雖然找了一堆的demo鄙煤,但是都沒(méi)有達(dá)到我想要的效果。正好趁著自己接了一個(gè)小項(xiàng)目茶袒,拿來(lái)練手梯刚。
這個(gè)項(xiàng)目主要的作用是熟悉 vue vue-router vuex 在初期搭建項(xiàng)目的時(shí)候該怎么配置,以及怎么去互相配合薪寓,xx.vue文件該怎么寫(xiě)亡资,如何創(chuàng)建和使用組件,vuex的state向叉,mutations锥腻,actions,getters怎么配合母谎,形成一個(gè)完整的流程瘦黑。
項(xiàng)目并不復(fù)雜,所以拿出來(lái)分享奇唤,希望對(duì)大家有幫助
源碼地址:https://github.com/bailicangdu/vue2-happyfri
路由配置
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) {
commit('REMBER_ANSWER', { id })
if (state.itemNum < state.itemDetail.length) {
commit('ADD_ITEMNUM', {
num: 1
})
}
},
getData({ commit, state }) {
ajax('GET', 'http://operating-activities.putao.com/happyfriday?active_topic_id=4').
then(res => {
commit('GET_DATA', {
res
})
})
},
initializeData({ commit }) {
commit('INITIALIZE_DATA')
}
}
mutations
const GET_DATA = 'GET_DATA'
const ADD_ITEMNUM = 'ADD_ITEMNUM'
const REMBER_ANSWER = 'REMBER_ANSWER'
const REMBER_TIME = 'REMBER_TIME'
const INITIALIZE_DATA = 'INITIALIZE_DATA'
const GET_USER_INFORM = 'GET_USER_INFORM'
export default {
[GET_DATA](state, payload) {
if (payload.res.httpStatusCode == 200) {
state.itemDetail = payload.res.topiclist;
}
},
[GET_USER_INFORM](state, payload) {
state.user_id = payload.res.users_id;
},
[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;
},
}
創(chuàng)建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
})
創(chuàng)建vue實(shí)例
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')