关于Vue.use()使用详解

问题

相信很多人在用Vue使用别人的组件时,会用到 Vue.use() 。例如:Vue.use(VueRouter)Vue.use(MintUI)。但是用 axios时,就不需要用 Vue.use(axios),就能直接使用。那这是为什么呐?

答案

因为 axios 没有 install
什么意思呢?接下来我们自定义一个需要 Vue.use() 的组件,也就是有 install 的组件,看完之后就明白了。

定义组件

生成模版 vue init webpack-simple custom-global-component
custom-global-component 为新建的文件夹名称
然后一路回车
cd custom-global-component 进入该文件夹
npm install 安装本次需要的模块
npm run dev 运行项目
如果能正常打开,进行下一步

这是当前项目目录:


项目目录-1.jpg

1.创建如下图中的文件夹和文件

项目目录-2.jpg

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>

6.看到这儿大家应该就明白了吧,用 axios时,之所以不需要用 Vue.use(axios),就能直接使用,是因为开发者在封装 axios 时,没有写 install 这一步。至于为啥没写,那就不得而知了。



作者:刘员外__
链接:https://www.jianshu.com/p/89a05706917a
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。
posted @   前端先锋  阅读(11560)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示