我們知道,使用 vue-cli
創建的項目結構是這樣的:
public/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
<noscript>
<strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>
src/main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
Vue.config.productionTip = false
new Vue({
router,
render: h => h(App)
}).$mount('#app')
src/App.vue
<template>
<div id="app">
<div id="nav">
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link>
<h1>您好,世界</h1>
</div>
<router-view/>
</div>
</template>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
}
#nav {
padding: 30px;
}
#nav a {
font-weight: bold;
color: #2c3e50;
}
#nav a.router-link-exact-active {
color: #42b983;
}
</style>
這些文件分別是什麼呢?
-
public/index.html
:打包的模板我們學習
webpack
的時候,知道webpack
配合着html-webpack-plugin
插件,可以實現打包我們的代碼的同時,使用html
模板,打包後會根據html
模板生成一個 新的html
文件,同時將我們打包後的腳本文件插入到這個新生成的html
文件中。 -
src/main.js
: 項目的入口文件我們一般在這個文件中引入我們需要的資源,路由等,然後得到一個
Vue
實例,同時將Vue
實例掛載到App.Vue
中的<div id='#app'></div>
。 -
src/App.vue
:根組件我們知道,我們現在創建的項目其實是一個單文件應用,也就是說,其實整個項目就只有一個頁面。這個
App.vue
就是我們項目的根組件,它是在main.js
中得到Vue
實例前被加載。
其實在 public/index.html
文件中也有一個 <div id='#app'></div>
,這只是個模板文件,在瀏覽器執行我們的項目的時候,這個 <div id='#app'></div>
會被更早的渲染,不過很快就被 src/App.vue
根組件中的 <div id='#app'></div>
覆蓋了。