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