vue-cli运行机制

理解 vue-cli 目录结构之后,我们看一下浏览器中的页面是如何显示出来的。打开 index.html 会发现首页代码干净整洁,没有任何页面上显示的数据,这可能会让一部分读者难以理解。下面开始讲解首页数据是如何渲染出来的。

在终端中输入“npm run dev”

最终执行的文件是 index.html,所以首先打开 index.html,代码如下。

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1.0">
  <title>vuetestdemo</title>
</head>
<body>
  <div id="app"></div>
  </body>
</html>

index.html 文件中只有一个 div 元素,没有其他内容,理论上运行 index.html 只会展示空白页面。实际上,还有其他内容,因为 Webpack 在 index.html 中自动引入了 main.js。

当运行 “npm run dev” 时,会自动在 index.html 中引入 main.js。

打开main.js

代码如下。

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

Vue.config.productionTip = false

new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

代码解析如下。

在 main.js 中,首先使用 es6 模块化方式引入了 Vue.js、App.vue、router.js。

“Vue.config.productionTip = false” 这行代码无须理会,它是控制台中提示环境的代码。

从 new Vue() 开始的代码就是我们所熟悉的,el 属性表示要控制 index.html 文件中 id 为 app 的元素。

router 表示在 Vue 实例中使用路由。 components 表示 Vue 实例中有一个 App 的组件。 template 则表示要渲染的内容。

在讲 Vue 生命周期时,当 Vue 同时出现 el 属性和 template 属性,template 中的内容会覆盖掉 el 属性中的内容,所以最终页面上渲染的内容是 template 中的内容,也即是 App 组件。

打开App.vue组件

App.vue 文件就是一个完整的组件,它是由三部分组成的,即 template、script、style。

template 是要渲染的 HTML 视图,在 script 中写逻辑代码,style 则为样式。

template 中只能有一个根节点。

页面中,最终渲染的数据代码如下。

<template>
  <div id="app">
    <img src="./assets/logo.png">
    <router-view/>
  </div>
</template>

<router-view/> 中显示的内容是由路由匹配规则规定的。

打开router文件夹下的index.js

代码如下。

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'HelloWorld',
      component: HelloWorld
    }
  ]
})

代码解析如下。

  • 引入 HelloWorld 组件。

  • 创建路由匹配规则,当路径为/时,显示HelloWorld组件。显示的位置就是App组件中的<router-view/>。

以上就是 vue-cli 的运行机制,建议观看视频,更有助于理解这一知识点。