路由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() } }