Vue系列 - 从创建vue到项目打包发布全过程总结

1 创建vue 项目

1.1 安装基本环境

1.安装node.js ,这里可自行查询官网

2.vue3.0 安装

npm install -g @vue/cli

1.2 vue3.0创建项目

vue create my-project

cd my-project

npm run serve

# 1.Manually select features

# 2.选择Router,Vuex,CSS Pre-processors,Linter / Formatter

# 3.css选择SCSS/SASS

# 4.Linter / Formatter选择prettier

# 5.In dedicated config files

安装成功后:

1.3 安装插件方法

安装element - ui

npm i element-ui -S

安装axios ,可以采用与面一样的命令,也可以采用下面的这种!

npm install --save axios

安装完成后会在package.json中显示版本信息 一般项目打包,不会打包插件文件夹node_models。 要重新下载这些包需要

npm install

其他相关命令按照src目录下的READ.md上的内容执行

# my-project

## Project setup 下载插件

npm install

### Compiles and hot-reloads for development

npm run serve

### Compiles and minifies for production

npm run build

### Lints and fixes files

npm run lint

### Customize configuration

See [Configuration Reference](https://cli.vuejs.org/config/).

2 打包vue项目

执行下列命令

执行npm run build

会生成dist目录

2.1 直接集成到springboot中

vue项目中首先配置vue.config.js到Vue根目录下(与package.json同级目录)

module.exports = {

publicPath: process.env.NODE_ENV === 'production'

? '/' //相对目录设置为了保证css,js等文件都访问到

: '/'

}

vue项目打包:

npm run build

打包后,引入标签变成了这样:

生成dist目录。将dist目录中的内容拷贝到springboot项目中的static目录下与templates目录下: 注意,通常springboot项目不能直接访问templates目录,需要通过thmyeleaf访问

引入thymeleaf依赖

org.springframework.boot

spring-boot-starter-thymeleaf

配置application.yml

server:

port: 8080

spring:

resources:

static-locations: classpath:/META-INF/resources/,classpath:/resources/static/,classpath:/static/,classpath:/public

thymeleaf:

prefix:

classpath: /templates # 访问template下的html文件需要配置模板,映射

cache: false # 开发时关闭缓存,不然没法看到实时页面

controller层

@Controller

public class IndexController {

@GetMapping({"/","/login"})

public String index(){

return "index";

}

}

即可通过开启springboot应用访问

3 vue单独发布到tomcat

首先应配置vue.config.js到Vue根目录下(与package.json同级目录)

module.exports = {

//在vue-cli.3.3版本后 baseUrl被废除了,因此这边要写成 publicPath

publicPath: process.env.NODE_ENV === 'production'

? '/VueTest/' //这里是tomcat下项目目录的名子,为了使发布时js,css等静态文件地址都找到

: '/'

}

然后vue项目运行打包

npm run build

生成dist目录。打开dist目录下的index.html 可以看到所有的静态文件地址都自动配置了"/VueTest/",这样发布时可以链接到。

在tomcat的webapps目录下新建VueTest,将dist目录中的内容复制进去 启动tomcat(bin/startup.bat) 成功访问

4 关于跨域问题

4.1 如果vue打包集成到springboot中

其实不用专门设置跨域,因为已经集到springboot中,只有一个端口

4.2 如果vue单独发布到tomcat中,需要解决跨域问题

这里是一个页面应用axios跨域的例子:

springboot中解决跨域问题:

@Controller

public class IndexController {

@GetMapping({"/","/login"})

public String index(){

return "index";

}

@GetMapping("/abc")

@CrossOrigin //该方法允许跨域

@ResponseBody

public Object abc(){

return "123";

}

}

直接采用SpringBoot的注解@CrossOrigin,Controller层在需要跨域的类或者方法上加上该注解即可。 其他花式方法见:https://blog.csdn.net/qq_43486273/article/details/83272500

5 小结

vue和springboot前后端分离开发,打包部署还有一些注意的点,后续还会做笔记!这里先把总体流程做一个总结。如果帮助到你,请记得给我点赞,谢谢!大家共同进步!