Vue.use()详解

転載先: https://www.jianshu.com/p/89a05706917a

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. 以下のようにフォルダーとファイルを作成します

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の読み込みファイル配下にインデックスを導入します

// 其中'./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なぜ書かれなかったのかについては不明です。

おすすめ

転載: blog.csdn.net/qq_48294048/article/details/125160597