你也许不知道的Vuejs - 单文件组件

by yugasun from yugasun.com/post/you-ma… 本文可全文转载,但须要保留原做者和出处。javascript

为何须要单文件组件

在以前的实例中,咱们都是经过 Vue.component 或者 components 属性的方式来定义组件,这种方式在不少中小规模的项目中还好,但在复杂的项目中,下面这些缺点就很是明显了:css

字符串模板:缺少高亮,书写麻烦,特别是 HTML 多行的时候,虽然能够将模板写在 html 文件中,可是侵入性太强,不利于组件解耦分离。 不支持CSS:意味着当 HTML 和 JavaScript 组件化时,CSS明显被遗漏了 没有构建步骤:限制只能使用 HTML 和 ES5 JavaScript,而不能使用预处理器。html

Vuejs 提供的扩展名为 .vue单文件组件 为以上全部问题提供了解决方案。vue

初识单文件组件

仍是利用 工欲善其事必先利其器 中的源码,在 src 目录下建立 hello.vue 文件,内容以下:java

<template>
  <h2>{{ msg }}</h2>
</template>
<script> export default { data () { return { msg: 'Hello Vue.js 单文件组件~' } } } </script>
<style> h2 { color: green; } </style>
复制代码

而后在 app.js 中引入使用:node

// ES6 引入模块语法
import Vue from 'vue';
import hello from './hello.vue';

new Vue({
  el: "#app",
  template: '<hello/>',
  components: {
    hello
  }
});
复制代码

此时项目是无法运行的,由于 .vue 文件 webpack 是无法是别的,它须要对应的 vue-loader 来处理才行,并且细心的朋友会发现 hello.vue 中用到了 ES6 语法,此时就须要用到相应的语法转化 loader 将 ES6 转化成主流浏览器兼容的 ES5 语法,这里就须要用到官方推荐的 babel 工具了。先安装须要的 loader:webpack

# hello.vue 文件中使用了 css,因此须要 css-loader 来处理,vue-loader 会自动调用
npm install vue-loader css-loader babel-loader babel-core babel-preset-env --save-dev
复制代码

有的人疑惑只是使用 babel-loader 为何还须要安装后面这么多工具呢,这是由于不少工具都是独立的,loader 只是为了配合 webpack 使用的桥梁,而这里 babel-corebabel-preset-env 才是实现 ES6 到 ES5 的核心。git

咱们再修改 webpack.config.js 配置以下:github

module.exports = {
  // ...
  module: {
    // 这里用来配置处理不一样后缀文件所使用的loader
    rules: [
      {
        test: /.vue$/,
        loader: 'vue-loader'
      },
      {
        test: /.js$/,
        loader: 'babel-loader'
      }
    ]
  }
}
复制代码

对于 babel 的配置,咱们还需在项目根目录下刚建立 .babelrc 文件来配置 Babel presets 和 其余相关插件,内容以下:web

{
  "presets": [ "env" ]
}
复制代码

可是虽然虽然都配置好了,项目仍是仍是会报错,报以下错误:

ERROR in ./src/hello.vue
Module build failed: Error: Cannot find module 'vue-template-compiler'
复制代码

有人就不高兴了,明明是按照官方提示安装了依赖,并正确的进行配置,为何仍是会报错呢?遇到错误不要怕,先阅读下错误是什么,很容易发现,是由于 Cannot find module 'vue-template-compiler',这是由于 vue-loader 在处理 .vue 文件时,还须要依赖 vue-template-compiler 工具来处理。

刚开始我不知道官方为何没有直接告诉用户须要安装这个依赖,经过阅读 vue-loader 才明白其 package.json 文件中是将 vue-template-compilercss-loader 做为 peerDependencies,而 peerDependencies 在安装的时候,并不会自动安装(npm@3.0+),只会给出相关警告,因此这个须要咱们手动安装的,固然在 .vue 文件中若是须要写 CSS,也必须用到 css-loader,这个也是在 peerDependencies 中。相关讨论:https://github.com/vuejs/vue-loader/issues/1158

知道问题了,直接安装下就能够了:

npm install vue-template-compiler css-loader --save-dev
复制代码

再次运行项目,页面中出现了咱们的内容,并没报错,ok,大功告成~

使用预处理器

咱们已经学会在 .vue 中写 css 了,那么若是使用 sass 预处理器呢?首先安装上篇文章中提到的模块:

npm install sass-loader node-sass --save-dev
复制代码

配置只需两步:

  1. 修改 webpack.config.jsvue-loader 配置
module.exports = {
    // ...
    module: {
      // 这里用来配置处理不一样后缀文件所使用的loader
      rules: [
        {
          test: /.vue$/,
          loader: 'vue-loader',
          options: {
            loaders: {
              // 这里也可使用连写方式,可是不利于自定义话参数配置
              // scss: 'vue-style-loader!css-loader!sass-loader'
              scss: [
                {
                  loader: 'vue-style-loader'
                },
                {
                  loader: 'css-loader'
                },
                {
                  loader: 'sass-loader'
                }
              ]
            }
          }
        },
        // ...
      ]
    }
  }

复制代码
  1. .vue 文件中的 style 标签,添加 lang="scss" 属性。

配置完后,就能够再 .vue 文件中,愉快地编写 sass 语法了。

加载全局设置文件

实际开发中,咱们在编写 sass 文件时,常常会将全局的 scss 变量提取出来,放到一个单独的文件中,可是这样就有个问题,每一个须要用到的组件,都须要手动 @import './styles/_var.scss' 进来,很是不友好。插件 sass-resources-loader 就很好地帮咱们解决这个问题,先安装一下:

npm install sass-resources-loader --save-dev
复制代码

而后修改 webpack.config.js 文件中 vue-loader 相关配置:

// ...
  {
    test: /.vue$/,
    loader: 'vue-loader',
    options: {
      loaders: {
        scss: [
          {
            loader: 'vue-style-loader'
          },
          {
            loader: 'css-loader'
          },
          {
            loader: 'sass-loader'
          },
          // 看这里,看这里,看这里
          {
            loader: 'sass-resources-loader',
            options: {
              // 这里的resources 属性是个数组,能够放多个想全局引用的文件
              resources: [resolve('./src/styles/_var.scss')]
            }
          }
        ]
      }
    }
  }
  // ...
复制代码

配置就完成了,咱们再来测试下。

src 目录下分别建立 hello1.vuehello2.vue 文件:

<!-- hello1.vue -->
<template>
  <h1>{{ msg }}</h1>
</template>
<script> export default { name: 'hello1', data () { return { msg: 'Hello Vue.js 单文件组件~' } } } </script>
<style lang="scss"> h1 { color: $green; } </style>

<!-- hello2.vue -->
<template>
  <h1>{{ msg }}</h1>
</template>
<script> export default { name: 'hello2', data () { return { msg: 'Hello Vue.js 单文件组件~' } } } </script>
<style lang="scss"> h1 { color: $red; } </style>
复制代码

而后建立一个 styles 目录,并在其中新建存放全局变量的文件 _var.scss:

$green: rgb(41, 209, 41);
$red: rgb(177, 28, 28);
复制代码

接下来,在 app.js 中引用两个组件:

import Vue from 'vue';
import hello1 from './hello1.vue';
import hello2 from './hello2.vue';

new Vue({
  el: "#app",
  template: '<div><hello1/><hello2/></div>',
  components: {
    hello1,
    hello2
  }
});
复制代码

从新运行项目就能够了。

有做用域的 style

单文件组件中为咱们提供了一个很是便利的功能,就是当 style 标签添加 scoped 属性时,标签内的样式将只做用于当前组件中的元素。

接着上面的例子,运行后会发现 hello1.vue 中的 h1 颜色并非想要的 $green 色,而是被 hello2.vue 中的样式覆盖了。因而分别在 hello1.vuehello2.vuestyle 标签上添加 scoped 属性,以下:

<!-- hello1.vue -->
<style lang="scss" scoped> h1 { color: $green; } </style>

<!-- hello2.vue -->
<style lang="scss" scoped> h1 { color: $red; } </style>
复制代码

这样一来咱们的两个 h1 标签颜色都显示正常了。

自定义块

在编写某些开源组件时,有时候咱们须要同时维护多个组件和组件说明,可是每次修改就要同时修改 .vue.md 文件,至关麻烦。.vue 文件的 自定义语言块 功能,就容许咱们将 markdown 说明同时写进 .vue 文件中,而后经过插件将其说明部分单独提取到相应的 .md 文件中,这样就能够同时维护说明文档和组件功能了。

好比咱们将 hello1.vue 文件修改以下:

<docs>
  # 标题
    这是标题内容,[仓库地址](https://github.com/yugasun/You-May-Not-Know-Vuejs)
  ## 子标题
    这是子标题内容
</docs>
<template>
  <h1>{{ msg }}</h1>
</template>
<script> export default { name: 'hello1', data () { return { msg: 'Hello Vue.js 单文件组件~' } } } </script>
<style lang="scss" scoped> h1 { color: $green; } </style>
复制代码

而后修改 webpack.config.js 配置:

const path = require('path');
// 引入相关插件
const ExtractTextPlugin = require('extract-text-webpack-plugin');

function resolve(dir) {
  return path.resolve(__dirname, dir);
}

module.exports = {
  // 入口文件
  entry: './src/app.js',
  // 编译输出文件
  output: {
    path: resolve('./'),
    filename: 'build.js'
  },
  resolve: {
    alias: {
      // 由于咱们这里用的是 require 引入方式,因此应该使用vue.common.js/vue.js/vue.min.js
      'vue$': 'vue/dist/vue.common.js'
    }
  },
  devServer: {
    // 这里定义 webpack-dev-server 开启的web服务的根目录
    contentBase: resolve('./')
  },
  module: {
    // 这里用来配置处理不一样后缀文件所使用的loader
    rules: [
      {
        test: /.vue$/,
        loader: 'vue-loader',
        options: {
          loaders: {
            scss: [
              {
                loader: 'vue-style-loader'
              },
              {
                loader: 'css-loader'
              },
              {
                loader: 'sass-loader'
              },
              {
                loader: 'sass-resources-loader',
                options: {
                  resources: [resolve('./src/styles/_var.scss')]
                }
              }
            ],
            docs: ExtractTextPlugin.extract('raw-loader')
          }
        }
      },
      {
        test: /.js$/,
        loader: 'babel-loader'
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin('docs.md')
  ]
}
复制代码

这里用到了 extract-text-webpack-plugin 导出 text 插件,和 raw-loader,分别都安装下就行。

而后运行构建命令 npm run build,等运行结束,根目录下会同时生成一个 docs.md 文件,这就是咱们想编写的说明文档。

总结

关于 单文件组件 就到这里,实际上 vue-loader 在处理 .vue 文件时,还有不少强大的功能,咱们这里只是带着你们感觉通常项目中如何使用,同时解释了下相关使用原理说明,更多的功能,建议阅读 vue-loader官方文档

源码在此

专题目录

You-May-Not-Know-Vuejs

相关文章
相关标签/搜索