Springboot整合Vue步骤以及遇到的问题

Springboot整合Vue

  • 分别创建一个Vue项目(idea默认项目即可)和Springboot项目,保证项目可运行

  •  在VUE项目中运行npm run build

  • build完成后会在对应目录下生成dist文件夹

  

  • 在springboot项目中resource下创建static和templates文件夹

  • 把dist文件夹目录下的文件放到springboot项目底下的resource/static目录底下

 

  •  此时访问本地项目地址下的index方法

 

@Controller
public class TestController {

  @Autowired
  private TestServiceImpl testService;

  @RequestMapping("/index")
  public String index() {
    return "index";
  }
}

编辑 

报错处理

  •  此时如果出现以下报错:

​编辑 

  • 在spring boot项目pom中引入依赖,load maven(刷一下),重启项目

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

 报错处理

  • 此时如果出现index页面空白,查看控制台报错js与css404,需要对前端打包进行配置:

前端修改

Vue2.0的打包配置:编辑config/index.js
const  path = require( 'path' )
 
module.exports = {
   build: {
     index: path.resolve(__dirname,  'dist/index.html' ),
     assetsRoot: path.resolve(__dirname,  'dist' ),
     assetsSubDirectory:  'static' ,
     assetsPublicPath:  './' ,
     productionSourceMap:  true
   },
   ......
}
Vue3.0的打包配置:编辑vue.config.js
module.exports = {
    publicPath: process.env.NODE_ENV === 'production' ? './' : './',
    outputDir: 'dist',
    assetsDir: 'static',
    ......
}
重新build前端项目:(新生成的文件内部不一样,重新按照之前的方式以及层级拷贝到springboot项目)
npm run build

后端修改

在config包下创建SpringWebMvcConfig类

@Configuration
public class SpringWebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
    }
}

 重启springboot项目重新访问index方法,就能打开vue项目中localhost:8080对应的页面

  • 0
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值