'Use Vue router only for specific subpages of Spring MVC-App
we've got an Spring Boot application which mainly uses Spring MVC to serve thymeleaf templates. Additionally, we needed to get more dynamic and reactivity, so we decided using Vue as a multi app approach: Some pages just contains a simple vue component and much static rendered html served from the thymeleaf template. Other pages are fully implemented as a vue app.
This is the flow: Thymleaf rendered HTML is given to the client and vue can hook into it creating the page built with vue.
Calling myapp.com/pageOne:
// pageOne.js
import { createApp } from "vue";
import PageOne from "./PageOne.vue";
const app = createApp(PageOne);
app.mount("#app");
<!-- thymeleaf template served by spring mvc -->
<body>
<main id="app"/>
</body>
<script src="/js/pageOne.js"></script>
Calling myapp.com/pageTwo:
// pageTwo.js
import { createApp } from "vue";
import PageTwo from "./PageTwo.vue";
const app = createApp(PageTwo);
app.mount("#app");
<body>
<main id="app"/>
</body>
<script src="/js/pageTwo.js"></script>
This multi page application approach is working nicely! However more and more vue-served pages are created. To get even more benefits from vue, I'll try to convert this Multi Page Application into a Single Page Application using vue-router. Therefore I do not need multiple vue apps, but only one. My approach is to load main.js with every thymleaf template:
// main.js
import { createApp } from "vue";
import router from "./router";
import App from "./App.vue";
const app = createApp(App);
app.use(router); // use router, configured with PageOne and PageTwo
app.mount("#app");
<body>
<main id="app"/>
</body>
<script src="/js/main.js"></script>
This is also working. Now I've got the problem that if I'm calling a thymeleaf only page, the vue app is also mounted and rendering its content into <main>-Tag. However, this is not desired, I need some mechanism to only mount my vue-app if its not a thymeleaf page but a page which is known by the vue-router. I think a possible could look like this:
// main.js
import { createApp } from "vue";
import router from "./router";
import App from "./App.vue";
const app = createApp(App);
app.use(router); // use router, configured with PageOne and PageTwo
// if its a thymleaf only page, we dont need to mount the vue app!
if (isPageServedByPage) {
app.mount("#app");
}
How can i determine isPageServedByPage? Could I look at what routes were defined at my router? Are there other approaches?
I apologize for this wall of text :)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
