在cmd命令窗口,到项目存放目录,运行如下命令:
vue init webpack spa1
spa1为项目名,根据实现输入即可。
注1:cmd命令行窗口显示中文乱码,多是因为cmd命令行窗口字符编码不匹配导致, 修改cmd窗口字符编码为UTF-8,命令行中执行:chcp 65001, 切换回中文:chcp 936, 这两条命令只在当前窗口生效,重启后恢复之前的编码。不能管。
接下来,安装程序会进入一问一答的安装模式:
1)Project name:项目名,默认是输入时的那个名称spa1,直接回车
2)Project description:项目描述,直接回车
3)Author:作者,随便填或直接回车
4)Vue build:选择题,一般选第一个
- Runtime + Compiler: recommended for most users //运行加编译,官方推荐
- Runtime-only: about 6KB lighter min+gzip, but templates (or any Vue-specific HTML) are ONLY allowed in .vue files - render functions are required elsewhere//仅运行时
5)Install vue-router:是否需要vue-router,Y选择使用,这样生成好的项目就会有相关的路由配置文件
6)Use ESLint to lint your code:是否用ESLint来限制你的代码错误和风格。N
7)Setup e2e tests with Nightwatch?:是否安装e2e测试 N
8)Should we runnpm installfor you after the project has been created? (recommended) (Use arrow keys)
> Yes, use NPM (选择该项即可)
> Yes, use Yarn
> No, I will handle that myself全部选择好回车就进行了生成项目,出现如下内容表示项目创建完成
#Project initialization finished!
#========================
安装完成后,在命令窗口,到项目目录,运行如下命令:
npm run dev
运行项目, 出现:Your application is running here: http://localhost:8080,表示运行成功,在浏览器地址栏输入http://localhost:8080即可查看。
| 命令 | 含义 |
|---|---|
| npm install | 下载“package.json”中dependencies和devdependencies中配置的所有依赖模块,并保存到项目的node_modules目录 |
| npm install xxx -g | 全局安装,下载依赖模块,并保存到%node_home%\node_global\node_modules目录下 |
| npm install xxx -S | 写入到package.json的dependencies对象,并保存到项目的node_modules目录 |
| npm install xxx -D | 写入到package.json的devDependencies对象,并保存到项目的node_modules目录 |
项目运行时默认使用的是8080端口,如果其他程序也使用该端口则会引发冲突,如果tomcat默认使用的也是8080,为避免冲突需要改变端口号。
打开项目目录下config/index.js文件,修改dev部分的port即可

2 做一个自定义组件Welcome

1) 在components下创建一个Welcome.vue自定义组件
- <template>
- <div class="hello">
- <h1>{{ msg }}h1>
- div>
- template>
-
- <script>
- //在es6中一个文件可以默认为一个模块,模块通过export向外暴露接口,实现模块间交互等功能
- //一个文件即模块中只能存在一个export default语句,导出一个当前模块的默认对外接口
- export default {
- name: 'Welcome',
-
- //组件的数据对象必须是函数形式定义
- //在定义data时也可以像HelloWorld中那样不带function关键字,效果是一样的
- //HelloWord中为简写形式
- data: function() {
- return {
- msg: 'Welcome to my App'
- }
- }
- }
- script>
-
- <style scoped>
- h1, h2 {
- font-weight: normal;
- }
- style>
2) 在router/index.js中配置路由,配置路由时要注意先导入组件
- import Welcome from '@/components/Welcome'
-
- export default new Router({
- routes: [
- {
- path: '/HelloWorld',
- name: 'HelloWorld',
- component: HelloWorld
- },
- {
- path: '/',
- name: 'Welcome',
- component: Welcome
- }
- ]
- })
我们将默认显示的HelloWorld,修改为了Welcome组件。运行系统观察页面展示。