Vue中的template配置项

1、简单介绍:

在 Vue.js 中,template 配置项是一个非常有用的特性,允许你直接在 Vue 实例或组件的定义中嵌入 HTML 模板字符串。这可以让你更方便地定义组件的结构,而不需要外部的 HTML 文件或者 <template> 标签对。

2、template的一些注意事项:

  • template中只能有一个根标签
<!DOCTYPE html>
<html lang="en">
<head>
<!--  option对象中的data-->
  <meta charset="UTF-8">
  <title>Vue中的template模板</title>
  <script src="./jsdocument/vue.js"></script>
</head>
<body>
<div id="app"></div>
<script>
  new Vue({
    data:{
      message:"Hello Vue!"
    },
    template:'<h1>{{message}}</h1><h1>{{message}}</h1>'
  }).$mount("#app")
</script>
</body>
</html>

可以看到报错:

正确的结果应该是:
template:'<div><h1>{{message}}</h1><h1>{{message}}</h1></div>'

  • template 编译后进行渲染时会将挂载位置的元素替换。
  • template 后面的代码如果需要换行的话, 建议将代码写到``符号当中, 不建议使用 + 进行字符串的拼接
<!DOCTYPE html>
<html lang="en">
<head>
<!--  option对象中的data-->
  <meta charset="UTF-8">
  <title>Vue中的template模板</title>
  <script src="./jsdocument/vue.js"></script>
</head>
<body>
<div id="app"></div>
<script>
  new Vue({
    data:{
      message:"Hello Vue!"
    },
    template: `
            <div>
              <h1>{{message}}</h1>
              <h1>{{message}}</h1>
            </div>
            `
  }).$mount("#app")
</script>
</body>
</html>
  • template可以省,同时代码直接写到html中
<!DOCTYPE html>
<html lang="en">
<head>
  <!--  option对象中的data-->
  <meta charset="UTF-8">
  <title>Vue中的template模板</title>
  <script src="./jsdocument/vue.js"></script>
</head>
<body>

<div id="app">
  <h1>{{message}}</h1>
  <h1>{{message}}</h1>
</div>

<script>
  new Vue({
    data:{
      message:"Hello Vue!"
    }
  }).$mount("#app")
</script>

</body>
</html>

注意:
这种方式不会产生像 template 那种的元素替换。虽然是直接写到 HTML 代码当中的, 但以上程序中的

<div id="app">
  <h1>{{message}}</h1>
  <h1>{{message}}</h1>
</div>

已经不是 HTML 代码了, 它是具有 Vue 语法特色的模板语句。 这段内容在 data 发生改变后都是要重新编译的。

  • vue在挂载时,可以不用$mount("#app"),可以直接使用,el选项。el 是 element 单词的缩写, 翻译为“元素”,el 配置项主要是用来指定 Vue 实例关联的容器。也就是说 Vue 所管理的容器是哪个。
<!DOCTYPE html>
<html lang="en">
<head>
  <!--  option对象中的data-->
  <meta charset="UTF-8">
  <title>Vue中的template模板</title>
  <script src="./jsdocument/vue.js"></script>
</head>
<body>

<div id="app">
  <h1>{{message}}</h1>
  <h1>{{message}}</h1>
</div>

<script>
  new Vue({
    data:{
      message:"Hello Vue!"
    },
    el:'#app'
  })
</script>

</body>
</html>
posted @ 2024-07-05 23:28  BLBALDMAN  阅读(8)  评论(0编辑  收藏  举报