单文件组件App.vue和html id重复为什么不出错?

我是vue初学者, 使用vue init webpack project_name创建了一个初始项目,并没有做初始改变, 直接使用npm run dev后开启了一个默认服务

版本信息:

λ npm list -g
E:\nodejs\node_global
├── vue-cli@2.9.6
├── webpack-cli@4.10.0
├── webpack-dev-server@4.10.0
└── webpack@5.74.0

初始化后文件列表

λ ls -al
total 1327
drwxr-xr-x 1 DELL 197121       0  8月 29 13:50 ./
drwxr-xr-x 1 DELL 197121       0  8月 29 18:11 ../
-rw-r--r-- 1 DELL 197121     242  8月 29 13:48 .babelrc
-rw-r--r-- 1 DELL 197121     156  8月 29 13:48 .editorconfig
-rw-r--r-- 1 DELL 197121      34  8月 29 13:48 .eslintignore
-rw-r--r-- 1 DELL 197121     820  8月 29 13:48 .eslintrc.js
-rw-r--r-- 1 DELL 197121     168  8月 29 13:48 .gitignore
-rw-r--r-- 1 DELL 197121     256  8月 29 13:48 .postcssrc.js
drwxr-xr-x 1 DELL 197121       0  8月 29 13:48 build/
drwxr-xr-x 1 DELL 197121       0  8月 29 13:48 config/
-rw-r--r-- 1 DELL 197121     282  8月 29 19:07 index.html
drwxr-xr-x 1 DELL 197121       0  8月 29 13:50 node_modules/
-rw-r--r-- 1 DELL 197121    2145  8月 29 13:48 package.json
-rw-r--r-- 1 DELL 197121 1164994  8月 29 13:50 package-lock.json
-rw-r--r-- 1 DELL 197121     486  8月 29 13:48 README.md
drwxr-xr-x 1 DELL 197121       0  8月 29 13:48 src/
drwxr-xr-x 1 DELL 197121       0  8月 29 13:48 static/

App.vue

<template>
  <div id="app">
    <img src="./assets/logo.png">
    <HelloWorld/>
  </div>
</template>

<script>
import HelloWorld from './components/HelloWorld'

// new Vue({
//   el: '#app',
//   components: {
//     'component-a': ComponentA,
//     'component-b': ComponentB
//   }
// })

export default {
  name: 'App',
  components: {
    HelloWorld
  }
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

main.js

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  components: { App },
  template: '<App/>'
})

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>todolist</title>
  </head>
  <body>
    <div id="app"></div>
    <!-- built files will be auto injected -->
  </body>
</html>

预期显示应该是:

<div id="app">
  <div id="app">
    <img src="./assets/logo.png">
    <HelloWorld/>
  </div>
</div>

实际上是:
image.png

我想问的是index.html中的id和App.vue单文件中的id出现了两次(这是项目初始化默认的,我没有改动),启动之后为什么没有报错?另外这个div标签h1 h2等标签出现的data-v-xxx是什么意思?
阅读 1.6k
1 个回答
  1. Vue 启动之后,原本的 <div id="app"> 会被替换掉,后面你看到的其实是 App.vue 渲染出来的 html DOM
  2. html 很宽容,即时有两个同 id 的节点,其实也不会报错,只是 js 操作的时候可能会有问题。
  3. data-v-xxx<style scoped> 产生的,vue 利用它生成选择器,达到覆盖全局样式的目的。
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题