Vue.use(js)
- 該js如果是物件
- 該物件里面要有一個install方法
- Vue.use就是呼叫里面的install方法
- 該js是一個function
- Vue.use時function會直接執行
作用:
- 可以在Vue的原型加一些東西
- 注冊全域組件等
使用
- 將hellow注冊為全域組件
- 在原型中添加$num= 123
- 在components中新建components.js
import HelloWorld from '@/components/HelloWorld.vue'
export default {
install: function (Vue) {
// 這里的Vue就是你呼叫install方法時傳遞過來的
// 可以在Vue原型中加一些東西
Vue.prototype.$num = 123
// 注冊全域組件
Vue.component(HelloWorld.name, HelloWorld)
}
}
- 在main.js中呼叫
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')
- Helloworld.vue
<template>
<div>
<h1>這里是HelloWord</h1>
<h2>{{ $num }}</h2>
</div>
</template>
<script>
export default {
name: 'HelloWorld'
}
</script>
<style></style>
結果:

- 該js為物件時,component.js寫法不一樣,其他均一樣
export default function (Vue) {
Vue.component(HelloWorld.name, HelloWorld)
Vue.prototype.$num = 123
}
Vue.use(VueRouter)就是這么實作的
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原型上
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/182878.html
標籤:python
上一篇:做網站或者網站改版的費用是多少
