LeoWangJ / blog

紀錄學習文章
1 stars 0 forks source link

vue 元素為何不能掛載在html與body上? #8

Open LeoWangJ opened 5 years ago

LeoWangJ commented 5 years ago
<body>
   <div id="app">
   </div>
</body>

let vm = new Vue({
  el: '#app',
  template: '<p>hello</p>'
})

通常我們在掛載Vue元素時會這樣寫,但為什麼我們不能將el掛載在body或html元素上呢? 原因是你的template裡面的html會替換掉

這一個元素,所以假設你在body上掛載元件時,會使得body被替換掉了,雖然省略body tag在html5是允許的,但省略可能會導致各家瀏覽器出現不明確的風險,所以還是盡量避免。

而且在vue源碼中也有做相關判斷,避免將el掛載在html與body上

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
  }