vue2 el不能是标签,必须是body内部一个标签的id吗

vue1中,el属性可以是标签,id,如:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>test</title>
</head>
<body>
    <div id="app"></div>
    <script src="vue.min.js"></script>
</body>
</html>
new Veu({
    el:"html"
});

目的是接收html内部所有的标签

然而2.0却只能用id,并且body内部的id

new Veu({
    el:"#app"
});

是我姿势不对,还是2.0改变了绑定方式?

阅读 17.7k
2 个回答

Vue 2.0 中源码如下:
src/entries/web-runtime-with-compiler.js

  el = el && query(el)

  /* istanbul ignore if */
  if (el === document.body || el === document.documentElement) {
    process.env.NODE_ENV !== 'production' && warn(
      `Do not mount Vue to <html> or <body> - mount to normal elements instead.`
    )
    return this
  }

query方法来着src/platforms/web/util/index.js
源码如下:

/**
 * Query an element selector if it's not an element already.
 */
export function query (el: string | Element): Element {
  if (typeof el === 'string') {
    const selector = el
    el = document.querySelector(el)
    if (!el) {
      process.env.NODE_ENV !== 'production' && warn(
        'Cannot find element: ' + selector
      )
      return document.createElement('div')
    }
  }
  return el
}

也就是说,Vue2.0在业务里面对HTML,body标签做了限制。

不推荐,也不能这样干(下面来自官网)

The provided element merely serves as a mounting point. Unlike in Vue 1.x, the mounted >element will be replaced with Vue-generated DOM in all cases. It is therefore not >recommended to mount the root instance to <html> or <body>.

缘由请看

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题