In the Vue documentation, I have seen opening and closing tags, but I've seen in other places where authors write components as self closing tags, like <some-component />
Is the practice of self-closing tags legal in Vue?
The v-html directive is a Vue. js directive used to update a element's inner HTML with our data. This is what separates it from v-text which means while v-text accepts string and treats it as a string it will accept string and render it into HTML.
Vue uses an HTML-based template syntax that allows you to declaratively bind the rendered DOM to the underlying component instance's data. All Vue templates are syntactically valid HTML that can be parsed by spec-compliant browsers and HTML parsers.
The key difference is that v-if conditionally renders elements and v-show **conditionally displays **elements. This means that v-if will actually destroy and recreate elements when the conditional is toggled. Meanwhile, v-show will always keep the element in the DOM and will only toggle its display by changing its CSS.
Component names should always be multi-word, except for root App components, and built-in components provided by Vue, such as <transition> or <component> . This prevents conflicts with existing and future HTML elements, since all HTML elements are a single word.
From the Vue style guide:
Components with no content should be self-closing in single-file components, string templates, and JSX - but never in DOM templates.
It's legal and strongly recommended by the Vue style guide: Vue Style Guide #self-closing components
Both the questions are answered above. But, I would like to point out what exactly is meant by no content in self closing tags.
When we use <div><p>Something</p></div>
, <p>
tag here is the content and hence, we cannot use div as a self closing tag.
Similarly in case of Vue JS components, you can also include content inside the component tags. e.g., <MyComponent><p>Something Else</p></MyComponent>
.
Then, in the component definition of <MyComponent>
, you have to includes to render the content passed wherever <MyComponent>
is used.
<MyComponent>
. i.e. If you do not have the <slot>
tag in the definition of your component, then your <MyComponent>
can be a self closing tag.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With