作者:李旭光
引用请标明出处
vue插件开发
Vue.use({install(Vues){}})
Vue.use
把给到的内容执行一下
举例
1 2 3 4
| function a(){ console.log('a') } Vue.use(a)
|
有 install 就执行 install
1 2 3 4 5 6 7
| function a(){ console.log('a') } a.install = function(){ console.log('b') } Vue.use(a)
|
再进一步
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| function a(){ console.log('a') } a.install = function(){ vue.mixin({ data(){ return { c:'this is mixin' } }, methods:{ } create(){ } }) } Vue.use(a)
|
vue.util.defineReactive()
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| vue.util.defineReactive()
var test = { testa: 1 } setTimeout(()=>{ test.testa = 2 },1000) vue.mixin({ beforeCreate(){ this.test = test } })
|
vue.extend vue.util.extend
vue.util.extend ===> 简单做了个拷贝,拷贝到一起
vue.extend ===> 获取到某个对象的实例
1 2
| let Constrator = vue.extend(obj) let vm = new Constrator()
|
手写vue-router
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| class HistoryRoute(){ constructor(){ this.current = null; } }
class vueRouter{ constructor(options){ this.mode = options.mode || 'hash' this.history = new HistoryRoute this.routes = options.routes||[] this.routesMap = this.createMap(this.routes) this.init() } init(){ if(this.mode == 'hash'){ location.hash?"":location.hash="/" window.addEventListener('load',()=>{ this.history.current = location.hash.slice(1) }) window.addEventListener('hashchange',()=>{ this.history.current = location.hash.slice(1) }) }else{ location.pathname?"":location.pathname="/" window.addEventListener('load',()=>{ this.history.current = location.hash.pathname }) window.addEventListener('popstate',()=>{ this.history.current = location.hash.pathname }) } } createMap(router){ return router.reduce((memo,current)=>{ memo[current.path] = current.component }) } }
vueRouter.install = function(Vue){ Vue.mixin({ beforeCreate(){ if(this.$options && this.$options.router){ this._root = this this._router = this.$option.router
Vue.util.defineReactive(this,'current',this._router.history) }else{ this._root = this.$parent._root } Object.defineProperty(this,'$route',{ get(){ return this._root._router } }) } }) Vue.component('router-view',{ render(h){ let current = this._self._root._router.history.current let routerMap = this._self._root._router.routeMap return h(routeMap[current]) } }) }
|