Vue3項(xiàng)目中給組件命名的方式詳解
1. 不使用插件,通過 export default 設(shè)置組件名
<template>
<div></div>
</template>
<script lang="ts">
export default {
name: "CustomComponentName"
}
</script>
<script lang="ts" setup>
// 組合式 API 邏輯
</script>
<style scoped></style>說明:
這是 Vue 原生支持的方式,通過 export default 中定義 name 屬性來設(shè)置組件名。
缺點(diǎn)是需要在 <script> 中額外寫一個對象,略顯冗余,且與 <script setup> 并用時存在兩個 script 標(biāo)簽。
2. 推薦方式:使用 vite-plugin-vue-setup-extend 插件(支持在 <script setup> 中直接寫 name)
<template> <div></div> </template> <script lang="ts" setup name="CustomComponentName"> // 組合式 API 邏輯 </script> <style scoped></style>
優(yōu)點(diǎn):
- 語法簡潔,組件名與邏輯寫在一起。
- 避免額外的 export default 塊,更適合 <script setup> 風(fēng)格。
3. 安裝與配置 vite-plugin-vue-setup-extend
(1)安裝依賴
npm install vite-plugin-vue-setup-extend -D
或使用其他包管理工具:
yarn add vite-plugin-vue-setup-extend -D # 或 pnpm add vite-plugin-vue-setup-extend -D
(2)配置 Vite(vite.config.ts)
import { defineConfig } from "vite"
import vue from "@vitejs/plugin-vue"
import VueSetupExtend from "vite-plugin-vue-setup-extend"
export default defineConfig({
plugins: [
vue(),
VueSetupExtend() // 啟用組件名擴(kuò)展
],
// 其他配置...
})(3)可選:TypeScript 支持
如果在 TypeScript 環(huán)境中希望獲得 name 屬性的類型提示,可在 env.d.ts 或 shims-vue.d.ts 中添加:
declare module "*.vue" {
import type { DefineComponent } from "vue"
const component: DefineComponent<{}, {}, any>
export default component
}該插件不強(qiáng)制要求類型聲明,但添加后可提升開發(fā)體驗(yàn)。
總結(jié)
| 方式 | 優(yōu)點(diǎn) | 缺點(diǎn) |
|---|---|---|
原生 export default | 無需插件,通用性強(qiáng) | 代碼冗余,與 <script setup> 配合不夠優(yōu)雅 |
vite-plugin-vue-setup-extend | 簡潔、現(xiàn)代化,適合 <script setup> 風(fēng)格 | 需要額外安裝插件及配置 |
推薦在 Vite + Vue 3 項(xiàng)目中使用 vite-plugin-vue-setup-extend,以保持代碼簡潔統(tǒng)一。
以上就是Vue3項(xiàng)目中給組件命名的方式詳解的詳細(xì)內(nèi)容,更多關(guān)于Vue3給組件命名方式的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
去除Element-Plus下拉菜單邊框的實(shí)現(xiàn)步驟
Element-Plus 是 Element UI 的 Vue 3 版本,它提供了一套完整的組件庫,在使用 Element-Plus 進(jìn)行開發(fā)時,我們可能會遇到需要自定義組件樣式的情況,本文將介紹如何使用 CSS 來去除 Element-Plus 下拉框的邊框,需要的朋友可以參考下2024-03-03
vue3+vite+ts使用monaco-editor編輯器的簡單步驟
因?yàn)楫呍O(shè)需要用到代碼編輯器,根據(jù)調(diào)研,我選擇使用monaco-editor代碼編輯器,下面這篇文章主要給大家介紹了關(guān)于vue3+vite+ts使用monaco-editor編輯器的簡單步驟,需要的朋友可以參考下2023-01-01
element plus中el-upload實(shí)現(xiàn)上傳多張圖片的示例代碼
最近寫項(xiàng)目的時候需要一次上傳多張圖片,本文主要介紹了element plus中el-upload實(shí)現(xiàn)上傳多張圖片的示例代碼,具有一定的參考價值,感興趣的可以了解一下2024-01-01
vue父元素點(diǎn)擊事件與子元素點(diǎn)擊事件沖突問題
這篇文章主要介紹了vue父元素點(diǎn)擊事件與子元素點(diǎn)擊事件沖突問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-01-01

