vue项目根目录下index.html中的id="app",与src目录下的App.vue中的id="app"为什么不会冲突

来源:互联网 发布:mac ai抠图教程视频 编辑:程序博客网 时间:2024/05/04 10:04

使用cli构建项目后,在根目录下有个index.html文件,其中有一行代码为:

// index.html<body>    <div id="app"></div>    <!-- built files will be auto injected --> </body>

而src目录下的App.vue中也有id="app"的代码

// APP.vue<template>  <div id="app">    <h1 class="title">头部</h1>    <router-view></router-view>  </div></template>
// main.jsnew Vue({  el: '#app',  router,  template: '<App/>',  components: {    App  }})

问题:
1.在main.js的初始化中,el:'#app'到底绑定的是哪个文件中的id='app'

2.为什么需要两个相同的id?


  • 已实验过,将index.htmlid="app"改成其他值,会报错。因此,el: '#app'绑定的是index.html中的id="app"的元素

  • 已检查过生成的页面代码,其中只有一个<div id="app"></div>,下面有一行注释<!-- built files will be auto injected -->,所以可以判断,此段来自index.html

    • index.html中的<div id="app"></div>是指定绑定元素根路径的

    • App.vue<div id="app"></div>则是用于具体注入绑定元素的内容

    • 由于Vue组件必须有个根元素,所以App.vue里面,根元素<div id="app"></div>与外层被注入框架index.html中的<div id="app"></div>是一致的

    • index.html中的#app指定绑定目标,而vue文件里的#app提供填充内容,两者在运行时指的是同一个DOM元素。


原创粉丝点击