Separate writing of a template

  • Just now, we have simplified the registration process of Vue components with syntax sugar, and there is another area that is a bit more cumbersome to write, the template module.
  • If we could write the HTML out of it and then mount it to the corresponding component, the structure would be clear.
  • Vue provides two scenarios for defining HTML module content:
    • use<script>The label
    • use<template>Label (recommended)

The first way is to write using script

 <! DOCTYPEhtml>
 <html lang="en">
 <head>
     <meta charset="UTF-8">
     <title>Title</title>
 </head>
 <body>
 ​
 <div id="app">
     <my_cpn></my_cpn>
 </div>
 ​
 <script type="text/x-template" id="cpn1">
     <div>
         <h2>I am heading</h2>
         <p>I am content hahahahaha</p>
         <p>I am content 2 hehe hehe hehe</p>
     </div>
 </script>
 ​
 <script src=".. /vue.js"></script>
 ​
 <script>
 
     Vue.component("my_cpn", {template:"#cpn1"
     })
     const app = new Vue({
         el:"#app".data: {message:"hello world"}})</script>
 </body>
 </html>
Copy the code

The second way to write using template (recommended)

 <! DOCTYPEhtml>
 <html lang="en">
 <head>
   <meta charset="UTF-8">
   <title>Title</title>
 </head>
 <body>
 ​
 <div id="app">
   <my_cpn></my_cpn>
 </div>
 ​
 <template id="cpn1">
   <div>
     <h2>I am heading</h2>
     <p>I am content hahahahaha</p>
     <p>I am content 2 hehe hehe hehe</p>
   </div>
 </template>
 ​
 <script src=".. /vue.js"></script>
 ​
 <script>
 ​
   Vue.component("my_cpn", {template:'#cpn1'
   })
 ​
   const app = new Vue({
     el:"#app".data: {message:"hello world"}})</script>
 </body>
 </html>
Copy the code

The effect is shown below