核心提示:使用cli构建项目后,在根目录下有个index.html文件,其中有一行代码为:// index.htmlbodyp id=app/p!-- built files will be auto inje...
使用cli构建项目后,在根目录下有个index.html文件,其中有一行代码为:
// index.html <body> <p id="app"></p> <!-- built files will be auto injected --> </body>
而src目录下的App.vue中也有id="app"的代码
// APP.vue <template> <p id="app"> <h1 class="title">头部</h1> <router-view></router-view> </p> </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"的元素 已检查过生成的页面代码,其中只有一个<p id="app"></p>,下面有一行注释<!-- built files will be auto injected -->,所以可以判断,此段来自index.html index.html中的<p id="app"></p>是指定绑定元素根路径的 App.vue的<p id="app"></p>则是用于具体注入绑定元素的内容 由于Vue组件必须有个根元素,所以App.vue里面,根元素<p id="app"></p>与外层被注入框架index.html中的<p id="app"></p>是一致的 index.html中的#app指定绑定目标,而vue文件里的#app提供填充内容,两者在运行时指的是同一个DOM元素。