Vue.use() 方法

1.本人在学习Vue时,会用到 Vue.use() 。例如:Vue.use(VueRouter)Vue.use(MintUI)。但是用 axios时,就不需要用 Vue.use(axios),就能直接使用。那这是为什么呐?然后就自己找原因。

答案: 因为 axios 没有 install。接下来我们自定义一个需要 Vue.use() 的组件,看完就明白了。

2.在 Loading.vue 中定义一个组件

<template>
    <div class="loading-box">
        Loading...
    </div>
</template>

3.在 index.js 中 引入 Loading.vue ,并导出

// 引入组件
import LoadingComponent from './loading.vue'
// 定义 Loading 对象
const Loading={
    // install 是默认的方法。当外界在 use 这个组件的时候,就会调用本身的 install 方法,同时传一个 Vue 这个类的参数。
    install:function(Vue){
        Vue.component('Loading',LoadingComponent)
    }
}
// 导出
export default Loading

4.在 main.js 中引入 loading 文件下的 index

// 其中'./components/loading/index' 的 /index 可以不写,webpack会自动找到并加载 index 。如果是其他的名字就需要写上。
import Loading from './components/loading/index'
// 这时需要 use(Loading),如果不写 Vue.use()的话,浏览器会报错,大家可以试一下
Vue.use(Loading)

5.在App.vue里面写入定义好的组件标签 <Loading></Loading>

<template>
  <div id="app">
    <h1>vue-loading</h1>
    <Loading></Loading>
  </div>
</template>
原文地址:https://www.cnblogs.com/huancheng/p/11321286.html