云驹博客

路漫漫其修远兮,吾将上下而求索。

0%

VueCLI(Vue脚手架)创建项目及配置

单文件组件

这是一个文件名为 Hello.vue 的简单实例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<template>
<p>{{ greeting }} World!</p>
</template>

<script>
module.exports = {
data: function () {
return {
greeting: "Hel1o",
};
},
};
</script>

<style scoped>
p {
font-size: 2em;
text-align: center;
}
</style>

即便你不喜欢单文件组件,你仍然可以把 JavaScript、CSS 分离成独立的文件然后做到热重载和预编译。

1
2
3
4
5
6
<!-- my-component.vue -->
<template>
<div>This will be pre-compiled</div>
</template>
<script src="./my-component.js"></script>
<style src="./my-component.css"></style>

创建一个项目

  1. 运行以下命令来创建一个新项目:

    1
    vue create hello-world
  2. 使用图形化界面

    1
    vue ui

了解更多

CSS 相关

CSS 局部生效

1
<style scoped></style>

预处理器

你可以在创建项目的时候选择预处理器 (Sass/Less/Stylus)。如果当时没有选好,内置的 webpack 仍然会被预配置为可以完成所有的处理。你也可以手动安装相应的 webpack loader:

1
2
3
4
5
6
7
8
# Sass
npm install -D sass-loader node-sass

# Less
npm install -D less-loader less

# Stylus
npm install -D stylus-loader stylus

然后你就可以导入相应的文件类型,或在 *.vue 文件中这样来使用:

1
2
3
<style lang="scss">
$color: red;
</style>

Vue.config.js 的配置

反向代理 devServer.proxy

示例:

1
2
3
4
5
6
7
8
9
10
11
12
module.exports = {
devServer: {
port: 8080, // 更改请求至路径的端口号
proxy: {
"/api": {
target: "<url>", // 改变请求头的自身域名
ws: true, // 是否请求WebSocket
changeOrigin: true, // 是否变更来源
},
},
},
};

了解更多

路径别名

@ == src 目录

多页面开发 pages

一个指定了 entry, template, filename, titlechunks 的对象 (除了 entry 之外都是可选的);

或一个指定其 entry 的字符串。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
module.exports = {
pages: {
index: {
// page 的入口
entry: "src/index/main.js",
// 模板来源
template: "public/index.html",
// 在 dist/index.html 的输出
filename: "index.html",
// 当使用 title 选项时,
// template 中的 title 标签需要是 <title><%= htmlWebpackPlugin.options.title %></title>
title: "Index Page",
// 在这个页面中包含的块,默认情况下会包含
// 提取出来的通用 chunk 和 vendor chunk。
chunks: ["chunk-vendors", "chunk-common", "index"],
},
// 当使用只有入口的字符串格式时,
// 模板会被推导为 `public/subpage.html`
// 并且如果找不到的话,就回退到 `public/index.html`。
// 输出文件名会被推导为 `subpage.html`。
// subpage 变量名自定义
subpage: "src/subpage/main.js",
},
};

了解更多