0
点赞
收藏
分享

微信扫一扫

vue项目根目录下index.html中的id=


使用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.js
new Vue({
el: '#app',
router,
template: '<App/>',
components: {
App
}
})

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

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


  • 已实验过,将​​index.html​​的​​id="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元素。


举报

相关推荐

0 条评论