1. 程式人生 > 程式設計 >vue自定義元件(通過Vue.use()來使用)即install的用法說明

vue自定義元件(通過Vue.use()來使用)即install的用法說明

在vue專案中,我們可以自定義元件,像element-ui一樣使用Vue.use()方法來使用,具體實現方法:

1.首先新建一個Cmponent.vue檔案

// Cmponent.vue
<template>
  <div>
    我是元件
  </div>
</template>
 
<script>
  export default {
 
  }
</script>
 
<style scoped>
  div{
    font-size:40px;
    color:#fbb;
    text-align:center;
  }
</style>

2.其次在同一目錄下建立index.js檔案,在這個檔案中使用install方法來全域性註冊該元件

import component from './Cmponent.vue'
const component = {
  install:function(Vue){
    Vue.component('component-name',component)
  } //'component-name'這就是後面可以使用的元件的名字,install是預設的一個方法
  
}
// 匯出該元件
export default component

3.使用

// 只要在index.js裡規定了install方法,就可以向其他ui元件庫那樣,使用Vue.use()來全域性使用
import loading from './index.js'
Vue.use(loading)
<template>
  <div>
   <component-name></component-name>
  </div>  
</template>

補充知識:如何在vue專案中自定義元件並在其他檔案引用?

1.執行環境:

編譯器:Visual Studio Code

Vue版本:2.9.6

在vue-cli搭建的專案目錄樹下

2.自定義vue元件

在src目錄下新建一個components目錄用於存放自定義元件:

vue自定義元件(通過Vue.use()來使用)即install的用法說明

建立存放自定義組建的目錄

新建一個vue檔案並編寫如下內容(以HelloWorld為例):

vue自定義元件(通過Vue.use()來使用)即install的用法說明

這裡的export default內容體內的name屬性值就是自定義的元件名,template標籤名內的內容是html標籤組成的集合,script標籤內是javascript程式碼定義動態效果,style標籤內的內容是元件的css樣式

編寫語句引入vue元件:

vue自定義元件(通過Vue.use()來使用)即install的用法說明

這裡的元件引入的語句是import HelloWorld from "@/components/HelloWorld";位於

在vue專案中引入自定義標籤<HelloWorld>:

vue自定義元件(通過Vue.use()來使用)即install的用法說明

最後的執行效果:

vue自定義元件(通過Vue.use()來使用)即install的用法說明

I am Hello World Component

這裡就是定義的元件內容

以上這篇vue自定義元件(通過Vue.use()來使用)即install的用法說明就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。