vue腳手架創建的項目中的 app.vue、main.js、index.html的關係

我們知道,使用 vue-cli 創建的項目結構是這樣的:
在這裏插入圖片描述

  1. 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>
  1. 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')
  1. 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>

這些文件分別是什麼呢?

  1. public/index.html :打包的模板

    我們學習 webpack 的時候,知道 webpack 配合着 html-webpack-plugin 插件,可以實現打包我們的代碼的同時,使用 html 模板,打包後會根據 html 模板生成一個 新的html文件,同時將我們打包後的腳本文件插入到這個新生成的 html 文件中。

  2. src/main.js : 項目的入口文件

    我們一般在這個文件中引入我們需要的資源,路由等,然後得到一個 Vue 實例,同時將 Vue實例掛載到 App.Vue 中的 <div id='#app'></div>

  3. 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> 覆蓋了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章