如何在VS Code中格式化Vue.js组件代码?
Hey there! Let's get your Vue components formatted properly—here's a step-by-step guide to resolve that non-working Shift+Alt+F issue with Vetur:
First, confirm Vetur is enabled
Open the Extensions panel (Ctrl+Shift+X on Windows/Linux, Cmd+Shift+X on Mac), find Vetur in your installed extensions list. If you see a "Disable" button, it's already enabled; if it says "Enable", click it and restart VS Code to activate the plugin.Set Vetur as the default formatter for Vue files
This is often the root cause—VS Code might not be using Vetur for Vue files by default:- Open Settings (Ctrl+, or Cmd+,), or click the gear icon in the bottom-left corner and select "Settings".
- In the search bar, type
[vue] default formatterto narrow down the relevant setting. - Under the
Editor: Default Formatterentry for Vue files, selectoctref.veturfrom the dropdown. - Alternatively, you can edit the
settings.jsonfile directly (click the curly braces icon in the top-right of the Settings panel) and add this configuration:"[vue]": { "editor.defaultFormatter": "octref.vetur" }
Tweak Vetur's formatting rules (optional)
If you want to customize how your code is formatted (like indent size, line breaks, or which parts of the Vue component to format), search forvetur formatin Settings. You'll find options to set default formatters for HTML, CSS, and JavaScript sections, plus toggles for enabling/disabling formatting for each part of the component.Test the formatting
Open your Vue component file, then press Shift+Alt+F (Windows/Linux) or Shift+Option+F (Mac). You can also right-click inside the editor and select "Format Document" to trigger it manually. If it works, your code should now be neatly formatted!Troubleshoot conflicts (if still not working)
If formatting still doesn't trigger, check for conflicting extensions—other formatting tools like Prettier might override Vetur. You can temporarily disable other formatting plugins to test, or adjust your settings to prioritize Vetur for Vue files. A quick restart of VS Code can also help resolve any lingering activation issues.
内容的提问来源于stack exchange,提问作者WoJ

