如何在 Vue 根实例中使用模板标签

How to use template tag with Vue root instance

我正在使用 Vue 增强 Web 应用程序中的页面。过去我编写过单个文件组件,我发现使用 <template> 标记在文件顶部定义 html 模板很方便。

有没有办法在定义 Vue 根实例时使用这个标签?或者我是否需要在 Vue 选项对象的模板 属性 中放置一个字符串?

您可以像这样使用 x-template 语法

<!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>

值得注意的是,如果您的编辑器不理解 x-template 块中的 html,您也可以使用 text/html

您还可以在页面中定义一些组件。当您从普通 html/js 升级页面但无法完全更改它时,这非常有用

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

似乎到 2020 年,您几乎可以使用 HTML5 标签 directly:

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

在某些情况下您可能不想使用 <template> 的原因是为了避免无效 HTML5 验证 and/or 呈现错误(请参阅 Vue.js DOM Template Parsing Caveats)。