<router-view/>与<router-view></router-view>有何区别?二者仅为语法糖还是实际存在差异?
<router-view/> and <router-view></router-view> in Vue Router Hey there! Great question—this is something that trips up a lot of Vue developers when they first start working with routing, so let’s break it down clearly.
Short Answer
For the vast majority of use cases, these two syntaxes are exact equivalents—they’re just different ways to write the same thing. The self-closing <router-view/> is essentially a shorthand for the empty double-tag version <router-view></router-view>.
When They Do Differ
The only time you’ll need to use the double-tag <router-view></router-view> is when you want to pass slot content to the routed component.
Vue Router’s <router-view> supports slots, which let you inject content into the component that’s rendered by the router. For example:
- If you want to provide fallback content that shows when no route is matched
- If your routed component defines named slots that need content from the parent template
Here’s a quick example of using slots with <router-view>:
<router-view> <!-- Fallback content when no route component is active --> <template #default> <div class="fallback">Select a page from the navigation!</div> </template> <!-- Named slot content for a routed component that expects it --> <template #sidebar> <aside class="sidebar">This is shared sidebar content!</aside> </template> </router-view>
In this case, you can’t use the self-closing <router-view/>—you need the opening and closing tags to wrap your slot templates.
A Quick Note on Vue Template Syntax
Vue’s template compiler allows self-closing tags for custom components (like <router-view/>) even though strict HTML doesn’t permit self-closing for non-void elements. So as long as you’re not passing any content/slots, either syntax works perfectly fine—it’s just a matter of personal preference or team style guidelines.
内容的提问来源于stack exchange,提问作者Javier

