路由Routervue
狀態管理Vuexgit
配置github
{ state: { cart: localStorage.getItem('cart') }, mutations:{ addCart:(state)=>{ } }, getter:{}, actions:{} }
使用vue-router
class KVuex { constructor (options) { this.state = options.state this.mutations = options.mutations this.actions = options.actions // 借用vue自己的響應式的通知機制 // state 會將須要的依賴收集在 Dep 中 this._vm = new KVue({ data: { $state: this.state } }) } commit (type, payload, _options) { const entry = this.mutations[type] entry.forEach(handler=>handler(payload)) } dispatch (type, payload) { const entry = this.actions[type] return entry(payload) } }
github.com/vuejs/vuexvuex
使用app
const routes = [ { path: '/', component: Home }, { path: '/book', component: Book }, { path: '/movie', component: Movie } ] const router = new VueRouter(Vue, { routes }) new Vue({ el: '#app', router })
class VueRouter { constructor(Vue, options) { this.$options = options this.routeMap = {} this.app = new Vue({ data: { current: '#/' } }) this.init() this.createRouteMap(this.$options) this.initComponent(Vue) } // 初始化 hashchange init() { window.addEventListener('load', this.onHashChange.bind(this), false) window.addEventListener('hashchange', this.onHashChange.bind(this), false) } createRouteMap(options) { options.routes.forEach(item => { this.routeMap[item.path] = item.component }) } // 註冊組件 initComponent(Vue) { Vue.component('router-link', { props: { to: String }, template: '<a :href="to"><slot></slot></a>' }) const _this = this Vue.component('router-view', { render(h) { var component = _this.routeMap[_this.app.current] return h(component) } }) } // 獲取當前 hash 串 getHash() { return window.location.hash.slice(1) || '/' } // 設置當前路徑 onHashChange() { this.app.current = this.getHash() } }