Vue.use() explanation

Reprinted at: https://www.jianshu.com/p/89a05706917a

Many people use it when using Vue to use other people's components Vue.use(). For example: Vue.use(VueRouter), Vue.use(MintUI). But axioswhen , you don't need to use it Vue.use(axios), you can use it directly. Why?

Because  axios there is no install

What does that mean? Next, we customize a required  Vue.use() component, that is, install some components. You will understand after reading this

Define components

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

This is the current project directory:

1. Create folders and files as shown below

2. Define a component in Loading.vue

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

 3.Introduce Loading.vue in index.js and export it

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

4.Introduce the index under the loading file in main.js

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

5. Write the defined component tag in App.vue <Loading></Loading> 

<template>
  <div id="app">
    <h1>vue-loading</h1>
    <Loading></Loading>
  </div>
</template>

6. Everyone should understand after seeing this. axiosWhen , the reason why you can use Vue.use(axios)it directly without using it is because the developer axiosdid not write installthis step when encapsulating it. As for why it was not written, that is unknown.

Guess you like

Origin blog.csdn.net/qq_48294048/article/details/125160597