為什么需要組件拆分呢?這樣才能更符合模塊化這樣一個理念。
首先是index.html,代碼如下:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no"> <title>sell</title> <link rel="stylesheet" type="text/css" href="static/css/reset.css"> </head> <body> <div id="app"></div> <-----------------------------------------這里才是有用的哦,記住這里,這是一個div,id='app' 這里是 A </body> </html>
app.vue文件:
<template> <div id="aaa"> <!------------------------------------------------------這里也要多注意下哦,稍后解釋 這里是 B <div class="header"> im header </div> <div class="container"> im container </div> <div class="footer"> im footer </div> </div> </template> <script> </script> <style> </style>
main.js文件
import Vue from 'vue';
import App from './App';
/*eslint-disable no-new*/
new Vue({
el:'#app', <!----------------------------------這里和下面一行都蠻重要的 這里是 C
render: h => h(App) <!----------------------------------還有這里哦 這里是 D
})
好,先讓我們看一下這么寫的效果和最后呈現在HTML的結構是什么樣的(太簡單了,我怕你們打我。。。。)
我腦子笨,你們原諒我連這點都想不明白,我剛開始就在糾結這三個問題。
1.index.html里面的那個帶id#app的div,為什么不會出現在dom結構里?
2.index.html里面的那個帶id#app的div,它與app.vue里面的id=‘#aaa’的div有什么關系?
3.為什么在main.js文件里面,用render: h => h(App)把它們掛載到#app里面,有的卻寫的是components:{app}?
正好加了一個vue的群,在群里提出了我的問題,里面的人告訴我說:
1.應該index.html 里面那個ID 只在node環境用 打包以后 就渲染成掛載的app.vue的頁面了.
2.app.vue 跟 index.html 里面的ID 不一定一樣 ,app.vue里面的id 會最終渲染到DOM結構里,並且寫的其他標簽 要放到那個div里面 而且template下級 只能有一個div.
3.
new Vue({
router,
store,
//components: { App } <!---------------------------------------------vue1.0的寫法
render: h => h(App) <!---------------------------------------------vue2.0的寫法
}).$mount('#app')
先說render:render
函數是渲染一個視圖,然后提供給el
掛載,如果沒有render那頁面什么都不會出來。
然后是 => 箭頭函數。是Es6中的新語法:(如果大家想更深入的了解,推薦一篇文章:鏈接:https://segmentfault.com/a/1190000009410939)
其實render: h => h(App)的意思, 首先 :表示 Vue 實例選項對象的 render 方法,它作為一個函數,接受傳入的參數 h 函數,返回 h(App) 的函數調用結果。等價於:
{ render: function(h) { return h(App); } }
其次:Vue 在創建 Vue 實例時,通過調用 render 方法來渲染實例的 DOM 樹。