function a() { console.log('函數自己的方法'); } a.install = function () { console.log('install的方法'); } Vue.use(a)//install的方法複製代碼
a.install = function (Vue) { Vue.mixin({ data(){ return{ //均可以在任何組件調用這個name name:"zxx" } } }) }複製代碼
//能夠拿到各個組件實例的this created(){ console.log(this); }複製代碼
//vue外面的對象 var test={ testa:1 } //進行數據綁定 Vue.util.defineReactive(test,'testa') //2秒以後改變 setTimeout(function(){ test.testa=333 },2000) a.install = function (Vue) { Vue.mixin({ //混入下面的組件 beforeCreate(){ this.test=test }, created(){ } }) }複製代碼
代碼前端
class History { constructor() { this.current = null } } class VueRouter { constructor(options) { this.mode = options.mode || 'hash'; this.routes = options.routes || []; this.history = new History; this.routesMap = this.createMap(this.routes) this.init() } init() { if (this.mode === 'hash') { //若是爲false的話,那麼執行後面的語句,改爲/ //若是爲true的話,執行'',不改變任何東西 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.pathname }) window.addEventListener('popstate', () => { this.history.current = location.pathname }) } } createMap(routes) { return routes.reduce((prev, item) => { prev[item.path] = item.component return prev }, {}) } } VueRouter.install=function(Vue){ Vue.mixin({ //全局混入了router實例,而且作了響應式綁定 beforeCreate() { if (this.$options && this.$options.router) { this._root = this; this._router = this.$options.router Vue.util.defineReactive(this, 'current', this._router.history) } else { this._root = this.$parent._root } } }) Vue.component('router-view', { render(h) { let current = this._self._root._router.history.current; console.log(current); let routesMap = this._self._root._router.routesMap console.log(routesMap); return h(routesMap[current]) } } ) } export default VueRouter複製代碼