在 Vue 中我們可以通過全局組件、局部註冊的方式來使用組件
全局註冊#
通過app.component
來創建全局組件
import { createApp } from 'vue'
import HelloWorld from './components/HelloWorld'
const app = createApp({})
// 全局註冊一個名為hello-wolrd的組件
app.component('hello-wolrd', HelloWorld);
一旦我們全局註冊了組件,我們就可以在任何地方使用這個組件:<hello-wolrd/>
值得注意的是全局註冊會使 Vue 失去
TypeScript
的支持,Vue 3 有一個 PR 擴展了全局組件的接口。目前,Volar 已經支持這種用法,我們可以通過在根目錄添加components.d.ts
文件的方式來添加全對局組件的TypeScript
的支持
declare module 'vue' {
export interface GlobalComponents {
HelloWorld: typeof import('./src/components/HelloWorld.vue')['default']
}
}
局部註冊#
我們可以直接從文件中引入 vue 組件使用,
在單文件組件中(SFC)
<template>
<HelloWorld msg="Welcome to Your Vue.js App"/>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue'
export default {
name: 'App',
components: {
HelloWorld
}
}
</script>
在 JSX 中
import HelloWolrd from './components/HelloWorld.vue'
export default {
name: "item",
render(){
return (
<HelloWolrd msg="Welcome to Your Vue.js App"/>
)
}
}
局部註冊的組件在其他組件中無法訪問,在其父組件或子組件或中均不可用,所以你需要在每個使用該組件的地方重新引入並註冊該組件
import HelloWolrd from './components/HelloWorld.vue'
但是這種直接導入組件的方式還有一個好處,如果我們導入的組件使用了typescript
,我們無需任何插件就可以在組件中獲得智能提示和類型檢查的功能
局部自動組冊#
可以看到局部註冊的優點是比較明顯的,但是每次使用我們都需要重複導入,但是如果你的組件很多,你的組件註冊代碼看起來可能比較冗長,我們可以使用unplugin-vue-components
,自動按需導入組件。它會按需導入組件,但是不再需要導入和組件註冊
該插件會自動對使用的組件生成一個
components.d.ts
從而獲得TypeScript
的支持,
安裝插件
- vite
// vite.config.ts
import Components from 'unplugin-vue-components/vite'
export default defineConfig({
plugins: [
Components({ /* options */ }),
],
})
- rollup
// rollup.config.js
import Components from 'unplugin-vue-components/rollup'
export default {
plugins: [
Components({ /* options */ }),
],
}
- webpack
// webpack.config.js
module.exports = {
/* ... */
plugins: [
require('unplugin-vue-components/webpack')({ /* options */ })
]
}
然後我們可以像往常一樣在模板中使用組件,它會自動進行下面的轉換
<template>
<div>
<HelloWorld msg="Hello Vue 3.0 + Vite" />
</div>
</template>
<script>
export default {
name: 'App'
}
</script>
轉換成
<template>
<div>
<HelloWorld msg="Hello Vue 3.0 + Vite" />
</div>
</template>
<script>
import HelloWorld from './src/components/HelloWorld.vue'
export default {
name: 'App',
components: {
HelloWorld
}
}
</script>
默認它會在src/components
目錄下查找組件,我們可以通過dirs
參數來自定義組件目錄,其他配置參考https://github.com/antfu/unplugin-vue-components#configuration
不同方案對比#
全局註冊 | 局部註冊 | unplugin-vue-components | |
---|---|---|---|
TypeScript 支持 | 定義components.d.ts 文件 | 默認支持 | 自動生成components.d.ts 文件 |
組件作用域 | 全局 | 局部 | 局部 |
使用方法 | 全局註冊後使用 | 局部註冊後使用 | 添加插件後使用 |