一、Vue Loader介绍
Vue Loader 是一个 webpack 的loader,它允许你以一种名为 单文件组件(SFCs)的格式撰写 Vue 组件。官方文档地址如下所示:
1、vue-loader 特性
- 默认支持 ES2015;
- 允许对Vue组件的组成部分使用其他 webpack loader,比如对<style> 使用Sass 和对 <template> 使用 Jade;
- 将 <style> 和 <template> 中的静态资源当作模块来对待,并使用 webpack loader 进行处理;
- 对每个组件模拟出 CSS 作用域;
- 支持开发期组件的热重载。
简言之,编写 Vue.js 应用程序时,组合使用 webpack 和 vue-loader 能带来一个现代、灵活并非常强大的前端工作流程。
二、项目示例
1、项目准备和组件安装
将 webpack-dev-server 项目复制为 single-file,安装 vue-loader 组件:
$ npm install vue-loader@14.2.4 -D
安装vue的模板解析器: vue-template-compiler,注意要安装对应的版本号,才能适配。
$ npm install vue-template-compiler@2.5.17 -D
2、在webpack中配置vue-loader
这里是在webpack.dev.config.js中配置vue-loader:
// node.js中内容模块
var path = require('path');
module.exports = {
// entry入口
entry: {
main: './src/main.js'
},
// output出口
output: {
path:path.resolve('./dist'), // 相对转绝对
filename: './bundle.js'
},
watch:true,
// 模块中的loader
module:{
loaders:[
{
test:/.css$/, // css结尾的
loader:'style-loader!css-loader' // 依次识别
},
{
test:/.vue$/,
loader:'vue-loader'
}
]
}
}
3、Vue组件规格
*.vue 文件是用户用 HTML-like 的语法编写的 Vue 组件。每个 *.vue 文件都包括三部分:组件结构(template—>html)、业务逻辑(script—>js)、组件样式(style—>css)。
vue-loader 是一个webpack的loader,可以将用上面*.vue格式编写的*.vue组件转换为 javascript 模块。
将App.js改写为App.vue。
<template>
<!-- template里一定是闭合标签 -->
<div class="app">
<h3>{{ msg }}</h3>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
</div>
</template>
<script>
export default {
data () {
return {
msg: '学习单页组件!'
}
},
methods:{
},
computed:{
}
}
</script>
<style>
h3 {
color: green;
}
.example {
color: red;
}
</style>
执行npm run dev,自动打开浏览器:http://localhost:8081/ 就访问到刚刚写好的App.vue页面了。

3、创建并挂载子组件
(1)创建子组件header
<template>
<div>
<h3>{{att}}</h3>
</div>
</template>
<script>
export default { // 组件抛出
name: "Header",
data() {
return {
att: "中美贸易战"
};
},
};
</script>
<style lang="css" scoped>
</style>
组件创建完成后抛出。
(2)挂载子组件
在App.vue文件中引入并挂载子组件:
<template>
<!-- template里一定是闭合标签 -->
<div class="app">
<h3>{{ msg }}</h3>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
<Header/>
</div>
</template>
<script>
// 1.导入组件
import Header from './Header.vue'
export default {
data () {
return {
msg: '学习单页组件!'
}
},
methods:{
},
computed:{
},
// 2.使用components挂载组件
components:{
Header
}
}
</script>
<style> /* 对全局样式起作用 */
h3 {
color: green;
}
.example {
color: red;
}
</style>
显示效果如下所示:

注意:vue组件中的style标签标有scoped属性时,表明style里的css只对当前组件的样式起作用 。