作用:
使用
import HelloWorld from '@/components/HelloWorld.vue'
export default {
install: function (Vue) {
// 這裡的Vue就是你呼叫install方法時傳遞過來的
// 可以在Vue原型中加一些東西
Vue.prototype.$num = 123
// 註冊全域性元件
Vue.component(HelloWorld.name, HelloWorld)
}
}
import Vue from 'vue'
import App from './App.vue'
import components from '@/assets/components.js'
Vue.use(components)
Vue.config.productionTip = false
new Vue({
render: h => h(App)
}).$mount('#app')
<template>
<div>
<h1>這裡是HelloWord</h1>
<h2>{{ $num }}</h2>
</div>
</template>
<script>
export default {
name: 'HelloWorld'
}
</script>
<style></style>
結果:
export default function (Vue) {
Vue.component(HelloWorld.name, HelloWorld)
Vue.prototype.$num = 123
}
vue-router原始碼
function install (Vue) {
if (install.installed && _Vue === Vue) { return }
install.installed = true;
_Vue = Vue;
var isDef = function (v) { return v !== undefined; };
var registerInstance = function (vm, callVal) {
var i = vm.$options._parentVnode;
if (isDef(i) && isDef(i = i.data) && isDef(i = i.registerRouteInstance)) {
i(vm, callVal);
}
};
Vue.mixin({
beforeCreate: function beforeCreate () {
if (isDef(this.$options.router)) {
this._routerRoot = this;
this._router = this.$options.router;
this._router.init(this);
Vue.util.defineReactive(this, '_route', this._router.history.current);
} else {
this._routerRoot = (this.$parent && this.$parent._routerRoot) || this;
}
registerInstance(this, this);
},
destroyed: function destroyed () {
registerInstance(this);
}
});
Object.defineProperty(Vue.prototype, '$router', {
get: function get () { return this._routerRoot._router }
});
Object.defineProperty(Vue.prototype, '$route', {
get: function get () { return this._routerRoot._route }
});
Vue.component('RouterView', View);
Vue.component('RouterLink', Link);
var strats = Vue.config.optionMergeStrategies;
// use the same hook merging strategy for route hooks
strats.beforeRouteEnter = strats.beforeRouteLeave = strats.beforeRouteUpdate = strats.created;
}
Object.defineProperty(Vue.prototype, '$router', {
get: function get () { return this._routerRoot._router }
});
Object.defineProperty(Vue.prototype, '$route', {
get: function get () { return this._routerRoot._route }
});
其核心就是以上兩行程式碼在install方法中將$router和route掛載到Vue原型上