Vue.use
problem
I believe many people in the use of someone else's components with Vue, will be used Vue.use()
.
For Vue.use(VueRouter)、Vue.use(MintUI)
example: .
But with axios
time, they do not need Vue.use(axios)
, can be used directly.
answer
Because axios
no install
.
What does that mean? Next we need a custom component Vue.use (), that is, there are components install, and after reading to understand
Build a simple project, the project is structured as follows:
In src/components/loading
creates two files in the directory, respectively index.js
, andloading.vue
loading.vue
The code is as follows
<template>
<div>
Loading.........
</div>
</template>
<script>
export default {
data() {
return {
}
},
components: {
}
}
</script>
<style>
</style>
index.js
Code:
import LoadingComponent from "./loading"
const Loading = {
// install 是默认的方法。当 use 这个组件的时候,就会调用本身的 install 方法,同时传一个 Vue 这个类的参数。
// install 方法的第一个参数就是Vue
install: function (Vue) {
this.util.init()
Vue.component('Loading', LoadingComponent)
console.log('component register to gobla context......')
},
// 在这里面可以添加其它的逻辑
util: {
init:function name() {
console.log('component init.........')
}
}
}
// 导出
export default Loading
use
Next, in main.js
the use of the assembly
import Vue from 'vue'
import App from './App.vue'
import Loading from './components/loading/index' // index可以不用写,默认加载index.js
// 全局注册组件 执行组件的install
Vue.use(Loading)
new Vue({
el: '#app',
render: h => h(App)
})
Loading in install method we have used in the assembly Vue.component
method to register the component
it can be used directly in App.vue
<template>
<div>
<h1>vue loading</h1>
<Loading />
</div>
</template>
<script>
//import Loading from './components/loading/loading.vue'
export default {
name: 'app',
data () {
return {
msg: 'Welcome to Your Vue.js App'
}
},
// 局部注册组件
// components:{
// Loading
// }
}
</script>
<style>
</style>
In this way we register the assembly in the global Vue, you can use directly on any instance of vue