spring boot使用vue+vue-router构建单页面应用


spring boot

http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/

vue

https://vuejs.org/guide/

vue-router

https://github.com/vuejs/vue-router/tree/dev/docs/zh-cn

使用vue+vue-router后不再由模版引擎或jsp生成页面,后台只进行json类型的数据交互。

实际第一次配置容易遇到一些问题:

1.url中含#号

解决方法:创建 router 实例时配置

const router = new VueRouter({
  mode: 'history',
  routes: [...]
})

http://router.vuejs.org/en/essentials/history-mode.html

2.参照https://github.com/vuejs/vue-router/blob/dev/docs/zh-cn/essentials/getting-started.md

点击链接跳转正常,浏览器显示地址正常

直接输入***/foo则报错,找不到页面

F12开启浏览器控制台发现:点击跳转并没有发送request 而是通过HTML5 History API

本质上是一个只有index.html的单页面应用

所以对应的后台要把所有404跳转到index.html

@SpringBootApplication
public class DemoApplication {

 @Bean public EmbeddedServletContainerCustomizer containerCustomizer() { return (container -> {
            ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/"); container.addErrorPages(error404Page); }); }

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

红色部分代码实现该功能

3.这样又出现了一个新的问题

随便输入url,即使不是vue-router中的url都会跳转到index,不再有404页面

解决方法

 
 
var router = new VueRouter();
router.map({
    'a':{},
    'b':{},
    // not found handler
    '*': {
      component: require('./../components/not-found.vue')
    }
});

配置其路由规则a跳转到XXX,b跳转到XXX(a,b存在对应),无对应跳转到not-found.vue作为404页面


参考实例https://github.com/kucharzyk/vuejs-java-starter 该项目使用中间件较多,其实并不需要node、npm(当时我还以为有node的一层服务器),只是方便管理

我也是刚开始尝试vue.js,写了个最基本的方便大家更好的理解https://github.com/wqbill/my-first-vue(灰常灰常基本,纯属展示一个解决完上述3个问题后的最基本框架Orz)

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM