What is the<template>Element?

  1. Get the instantiated HTML element (not just a string) via the

    <template id="tpl">
      <div>a</div>
      <div>b</div>
    </template>
    <script>
      const tpl = document.getElementById('tpl')
      tpl.content // document-fragment
      tpl.content.children[0].outerHTML // <div>a</div>
    </script>
    Copy the code
  2. The SRC attribute of the img element under

  3. Script and CSS rules under

For more information see: Semantic HTML: The NEW HTML5 Tag — Template

v-ifcollocation<template>

<div v-scope="App"></div>

<script type="module">
  import { createApp } from 'https://unpkg.com/petite-vue?module'

  createApp({
    App: {
      $template: `
      <template v-if="status === 'offline'">
        <span> OFFLINE </span>
      </template>
      <template v-else>
        <span> ONLINE </span>
      </template>
      `,
    }
    status: 'online'
  }).mount('[v-scope]')
</script>
Copy the code

The first rendering process is as follows:

  1. App.$template will be rendered into the DOM tree via the resolveTemplate method in walk.ts

    <div v-scope="App">
       <template v-if="status === 'offline'">
         <span> OFFLINE </span>
       </template>
       <template v-else>
         <span> ONLINE </span>
       </template>
    </div>
    Copy the code
    1. Enter thedirectives/if.tsIdentify the attachedv-if,v-elseElement and remove them from the DOM tree
    2. According to the conditional expressionstatus === 'offline'Used for Dettached nodes<template v-else></template>Create a Block object based on it
    <div v-scope="App">
    </div>
    Copy the code
  2. The

    <div v-scope="App">
    </div>
    Copy the code
  3. Finally, the block object is inserted into the parent and precedes the anchor element in the directives/if.ts

    <div v-scope="App">
       <span> ONLINE </span>
    </div>
    Copy the code

summary

  1. So we’re using theta<template>The element itself features online parsing users invisible (you can’t see me, you can’t see me :D), and avoiding as<img src="logo.png">Problems with sending invalid requests;
  2. Due to the<template>Is in theblock.tsProcessing to get the template, thereforev-forcollocation<template>The principle andv-ifIt’s consistent.

Incorrect use

While

<div v-scope="App"></div>

<script type="module">
  import { createApp } from 'https://unpkg.com/petite-vue?module'

  createApp({
    App: {
      $template: ` 
        `,}status: 'online'
  }).mount('[v-scope]')
</script>
Copy the code

The root block object corresponds to

, and

<div v-scope="App">
  <template>
    <div>Hello</div>
  </template>
</div>
Copy the code

Used when the text Hello cannot be seen.

conclusion