问题
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?
回答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
回答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).
来源:https://stackoverflow.com/questions/50205341/how-to-use-template-tag-with-vue-root-instance