Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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://vuejs.org/v2/guide/components-edge-cases.html#X-Templates


Solution 2:

Seems as of 2020, you can pretty much use HTML5 tag directly:

<template v-if="ok">
    <h1>Title</h1>
    <p>Paragraph 1</p>
    <p>Paragraph 2</p>
</template>

The reason you might not want to use <template> in some cases is to avoid invalid HTML5 validation and/or rendering errors (see Vue.js DOM Template Parsing Caveats).


Post a Comment for "How To Use Template Tag With Vue Root Instance"