web前端

vue-cli 单文件组件

2017-08-07  本文已影响0人  NathanYangcn

在 Vue 项目初始化完成之后(vue-cli),来看一看该环境中 HTML, CSS, JS 三者的关系

本文将按照以下顺序进行查看:

一、index.html(首页)

首先,来看 index.html,IDE 内代码如下

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>first-test-vue</title>
  </head>
  <body>
    <div id="app"></div>
    < !-- built files will be auto injected -->
  </body>
</html>
这里并未看到引入打包文件 bundle.js 的标签,但是它说了:< !-- built files will be auto injected --> ,意思是:打包文件将会被自动注入。

那去 http://localhost:8080/#/ 看看生成的页面的 HTML 结构是怎样的,代码如下

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>first-test-vue</title>
    <style type="text/css">...<style>
    <style type="text/css">...<style>
  </head>
  <body>
    <div id="app"></div>
    < !-- built files will be auto injected -->
    <script type="text/javascript" src="/app.js"><script>
  </body>
</html>

这里 head 标签中多了 style 标签,body 标签中多了 script 标签

看来,会自动把 JS, CSS 全部注入了 HTML

首页没有需要特别关心的,接下来去看源代码目录

二、src/ (除首页之外的源代码的目录)

其次,来到 src 目录下,该目录存储的内容为:除首页(index.html)之外的所有源代码

├── src                      # 除首页之外的,所有源代码
    ├── assets                   # 存放代码之外的资源
    ├── components               # 除主组件之外的,所有组件
    ├── router                   # 路由
    ├── App.vue                  # 主组件:页面入口文件
    └── main.js                  # 程序入口文件

三、src/main.js (JS 入口文件)

第三,看 main.js,程序入口文件,代码如下

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

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  template: '<App/>',
  components: { App }
})
3.1 该 Vue 实例中的3个属性分别如下:
  1. el —— 挂载元素
  2. template —— 模板
  3. components —— 组件
3.2 其中:

模板(template)将会 替换 挂载的元素(el),挂载元素的内容都将被忽略
模板(template)中的 <App/> 是由 组件(components)中的 { App } 来定义的
组件(components)中的 { App } 是由 import App from './App' 来引入的
import App from './App' 中的 './App' 就是 src/ 目录下的 App.vue 组件
App.vue 组件 就是 Vue 的单文件组件,最终定义了 模板(template)中的 <App/>

补充:

import
Vue 单文件组件

四、src/App.vue (组件

第四,看 App.vue 组件,也就是 .vue 组件文件,代码如下

<template>
  <div id="app">
    ![](./assets/logo.png)
    <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: 'app'
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
4.1 该单文件组件包括三个根标签:
  1. <template></template> 2. <script></script> 3. <style></style>
4.2 其中:
  1. template 标签
  1. script 标签
  1. style 标签
4.3 最终:

.vue 文件将 HTML, CSS, JS 三部分组织到一个文件内,从而实现了对一个组件的封装
一个 .vue 文件就可以是一个组件
一个 .vue 组件的固定形式就是以上所述

五、总结

5.1 src/ 目录是:除首页外的所有源代码目录
5.2 main.js 会将组件注入 index.htm 首页中,当然也说明了如何引入组件:import 引入组件;components 获取组件;template 使用组件
5.3 一个 Vue 单文件组件,包括三个根标签:template, script, style
5.4 script 标签必须包含 export default 默认导出一个对象
5.5 script 标签导出的对象中的 data 属性应该是一个函数
5.6 style 标签中的属性 scoped 限定了样式的作用域

上一篇 下一篇

猜你喜欢

热点阅读