Search code examples
vue.jshtml5-template

How to use template tag with Vue root instance


I am enhancing a page in a web application using Vue. In the past I have written single file components and I've found it convenient to define the html template at the top of the file using a <template> tag.

Is there a way to use this tag when defining a Vue root instance? Or do I need to put a string in the template property of the Vue options object?


Solution

  • You can use the x-template syntax, like so

    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width">
      <title>JS Bin</title>
      <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    </head>
    <body>
      
      <script type="text/x-template" id="message-template">
            <div >
               {{message}}
            </div>
        </script>
      
      <div id="app"> </div>
      
     <script>
         var graphapp = new Vue({
                el: "#app",            
                data: {
                    message: "hi there"
                },
                template: "#message-template"
         });   
      </script>
       
    </body>
    </html>
    

    worth noting, if your editor doesn't understand html inside the x-template block you can use text/html also.

    You can also define a number of components in the page also. This is super useful when you are upgrading a page from plain html/js but can't fully change it over

    Refer to: https://v2.vuejs.org/v2/guide/components-edge-cases.html#X-Templates