問題
在Vue項目的開發中,我們經常遇到一個問題,創建新組件時要自己輸入基本的框架,比如:
<template><div class="page-box"></div>
</template><script>
export default {name: '',data() {return {}}
}
</script><style scoped>
.page-box {}
</style>
那有沒有辦法像生成一個html文件那樣在vscode里快速生成Vue組件框架呢?
實踐
根據我的需要,我選擇了比較簡單的方案:使用 VSCode 的用戶代碼片段功能。
- 打開命令面板:
- Windows/Linux: Ctrl + Shift + P
- Mac: Cmd + Shift + P
- 輸入并選擇:「Snippets: Configure Snippets」
- 選擇「vue」或「新建全局代碼片段文件」
- 添加以下內容:
{"Vue 2 Component": {"prefix": "v2","body": ["<template>"," <div class=\"$1\">"," $2"," </div>","</template>","","<script>","export default {"," name: '$3',"," data() {"," return {"," $4"," }"," },"," methods: {"," $5"," }","}","</script>","","<style scoped lang=\"${6:less}\">",".$1 {"," $7","}","</style>"],"description": "Vue 2 標準組件結構"},
}
使用方法:在 .vue 文件中輸入 v2,按 Tab 鍵自動補全模板。
其他方案(from DeepSeek)
以下是快速創建 Vue 組件文件的幾種高效方法,適用于不同開發場景:
方法 1:使用 IDE/編輯器模板(最推薦)
VSCode 用戶
-
安裝插件:
Vue VSCode Snippets
(提供代碼片段)File Templates
(自定義文件模板)
-
創建模板文件:
在項目根目錄新建.vscode/templates/vue-component.template
:<template><div class="${1:component-name}">${2:<!-- 內容區 -->}</div> </template><script> export default {name: '${3:ComponentName}',${4:// 組件邏輯} } </script><style scoped lang="${5:less}"> .${1:component-name} {${6:/* 樣式 */} } </style>
-
快捷鍵生成:
右鍵 →New File from Template
選擇模板
方法 2:命令行工具(適合批量創建)
使用 plop.js(自動化腳手架)
- 安裝:
npm install -g plop
- 創建
plopfile.js
:module.exports = function (plop) {plop.setGenerator('component', {description: 'Create a Vue component',prompts: [{type: 'input',name: 'name',message: 'Component name (PascalCase):'}],actions: [{type: 'add',path: 'src/components/{{pascalCase name}}.vue',templateFile: 'templates/component.hbs'}]}); }
- 運行:
plop component
方法 3:NPM 腳本(極簡版)
在 package.json
中添加腳本:
"scripts": {"new:component": "bash ./scripts/new-component.sh"
}
創建 scripts/new-component.sh
:
#!/bin/bash
echo "Enter component name (PascalCase):"
read namecat > "src/components/${name}.vue" <<EOF
<template><div class="${name,}"><!-- 內容 --></div>
</template><script>
export default {name: '${name}'
}
</script><style scoped>
.${name,} {}
</style>
EOFecho "Component ${name}.vue created!"
運行:
npm run new:component
方法 4:在線工具生成
- Vue Component Generator(網頁工具):
https://vue-component-generator.netlify.app/
勾選選項后直接下載.vue
文件
不同場景推薦方案
場景 | 推薦方案 | 優點 |
---|---|---|
少量組件 | IDE 模板 | 無需配置,即開即用 |
大型項目 | plop.js | 支持批量生成,統一代碼風格 |
團隊協作 | 共享代碼片段/Snippet | 確保團隊規范一致 |
需要高度自定義 | 自定義 Shell/Python 腳本 | 靈活控制生成邏輯 |
附:標準 Vue 3 組件模板(組合式 API)
<template><div class="component-name"><h1>{{ msg }}</h1></div>
</template><script setup>
import { ref } from 'vue'const msg = ref('Hello World')
</script><style scoped>
.component-name {color: var(--primary-color);
}
</style>