vue实践录:创建vue工程

本文讲述使用 vue-cli脚手架创建工程,以期对 vue 有一定的认识。

建工程

安装vue-cli全局脚手架:

1
npm install --global vue-cli

创建 demo 工程

1
vue init webpack demo

一路回车即可,到测试那些步骤可选n。过程输出:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
$ vue init webpack demo

? Project name (demo)
? Project name demo
? Project description (A Vue.js project)
? Project description A Vue.js project
? Author (Late Lee <li@latelee.org>)
? Author Late Lee <li@latelee.org>
? Vue build standalone
? Install vue-router? (Y/n)
? Install vue-router? Yes // !!! 上面全部是直接回车
? Use ESLint to lint your code? (Y/n) n
? Use ESLint to lint your code? No
? Set up unit tests (Y/n) n
? Set up unit tests No
? Setup e2e tests with Nightwatch? (Y/n) n
? Setup e2e tests with Nightwatch? No
? Should we run `npm install` for you after the project has been created? (recom
? Should we run `npm install` for you after the project has been created? (recom
mended) npm

vue-cli · Generated "demo".

。。。

# Project initialization finished!
# ========================

To get started:

cd demo
npm run dev

Documentation can be found at https://vuejs-templates.github.io/webpack

根据提示,执行:

1
2
cd demo
npm run dev

最后输出结果:

1
2
3
95% emitting DONE  Compiled successfully in 2962ms10:34:06

I Your application is running here: http://localhost:8080

访问http://127.0.0.1:8080/即可看到效果。

如需发布,执行:

1
npm run build

得到dist目录,放到 web 服务器静态资源目录即可。

知识点

  • 使用npm run dev运行服务时,修改 vue 文件,会即时生效(热部署),调试、观察效果十分方便。但一些初始化的配置文件修改除外。
  • 每个.vue文件,即为独立的 vue 组件。包含 template、script、style(每个组件均为独立,互不干扰)。
  • 开发时依赖库多,运行时只依赖 vue 和 vue-router。
  • 文件.env.development.env.production分别为开发环境和生产环境,可设置变量,代码中直接用process.env.VUE_APP_URL访问。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
export default {
data() {
return { // 使用return,用于当前组件的变量声明(如果有全局的同名变量,先使用此处的)
name: "latelee",
age: 22
};
},
computed: {

},
methods: {

},
mounted() {

}
};
1
2
3
import model from "@/common/model";
作用:
@ 等价于 /src 这个目录,避免写麻烦又易错的相对路径