天天看點

vue2.0(新手)第一個坑--do not mount Vue to <body>!!!

import Vue from 'vue';
import App from './App';

/* eslint-disable no-new */
new Vue({
  el: '#app',
  template: '<App/>',
  components: { App }
});
           
vue2.0(新手)第一個坑--do not mount Vue to &lt;body&gt;!!!

這是vue2.0的最新寫法,我們看到的是vue項目的主入口main.js,template是将會替換el的挂載元素的模闆

差別一定是:el對應的 一定是一個css選擇器,如果還是html 或者body元素,如下圖:

vue2.0(新手)第一個坑--do not mount Vue to &lt;body&gt;!!!
import Vue from 'vue';
import App from './App';

/* eslint-disable no-new */
new Vue({
  el: 'body',
  components: { App }
});
           

浏覽器将會報錯:

vue2.0(新手)第一個坑--do not mount Vue to &lt;body&gt;!!!
[Vue warn]: Do not mount Vue to <html> or <body> - mount to normal elements instead. 
warn @ vue.common.js?e881:509
vue.common.js?e881:5929 Download the Vue Devtools for a better development experience:
https://github.com/vuejs/vue-devtools
           

,google translate:

vue2.0(新手)第一個坑--do not mount Vue to &lt;body&gt;!!!

不要将Vue挂載到<html>或<body> - mount到普通元素。

官方文檔是這麼解釋的:

提供的元素隻能作為挂載點。不同于 Vue 1.x,所有的挂載元素會被 Vue 生成的 DOM 替換。是以不推薦挂載root執行個體到 

<html>

 或者 

<body>

 上。

繼續閱讀