[Vuejs]-Usage of <template> in front end development

3👍

The <template> element in general

The HTML Content Template (<template>) element is a mechanism for
holding client-side content that is not to be rendered when a page is
loaded but may subsequently be instantiated during runtime using
JavaScript.

Think of a template as a content fragment that is being stored for
subsequent use in the document. While the parser does process the
contents of the <template> element while loading the page, it does so
only to ensure that those contents are valid; the element’s contents
are not rendered, however.

##The <template> element in Vue.js

You can find more information about it in the Vue.js guide. For example, in the context of v-if.

Conditionally render the element based on the truthy-ness of the expression value. The element and its contained directives / components are destroyed and re-constructed during toggles. If the element is a <template> element, its content will be extracted as the conditional block.

What that means exactly can be seen in this example:

<div v-if="true">Foo</div>
<template v-if="true">Bar</template>

which will result in:

<div>Foo</div>
Bar

The <template> element will not be part of the DOM after if has been processed by Vue.js anymore. The same applies when using the v-for directive on <template>.

👤str

1👍

See MDN:

The HTML Content Template (<template>) element is a mechanism for
holding client-side content that is not to be rendered when a page is
loaded but may subsequently be instantiated during runtime using
JavaScript.

Think of a template as a content fragment that is being stored for
subsequent use in the document. While the parser does process the
contents of the <template> element while loading the page, it does
so only to ensure that those contents are valid; the element’s
contents are not rendered, however.

or the HTML specification:

The template element is used to declare fragments of HTML that can be cloned and inserted in the document by script.

In a rendering, the template element represents nothing.

Leave a comment