Vuejs 单文件组件实例详解

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

字符串模板:缺乏高亮,书写麻烦,特别是 HTML 多行的时候,虽然可以将模板写在 html 文件中,但是侵入性太强,不利于组件解耦分离。

不支持CSS:意味着当 HTML 和 JavaScript 组件化时,CSS明显被遗漏了

没有构建步骤:限制只能使用 HTML 和 ES5 JavaScript,而不能使用预处理器。

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

初识单文件组件

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

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

然后在 app.js 中引入使用:

// 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 :

# 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-core 和 babel-preset-env 才是实现 ES6 到 ES5 的核心。

我们再修改 webpack.config.js 配置如下:

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

对于 babel 的配置,我们还需在项目根目录下刚创建 .babelrc 文件来配置 Babel presets 和 其他相关插件,内容如下:

{ "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-compiler 和 css-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

配置只需两步:

修改 webpack.config.js 中 vue-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' } ] } } }, // ... ] } }

给 .vue 文件中的 style 标签,添加 lang="scss" 属性。

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

加载全局设置文件

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/ppwxg.html