I am developing an SPA using Vue 2.0. The components developed so far are for the "desktop" browsers, for example, I have
Main.vue, ProductList.vue, ProductDetail.vue,
I want another set of components for the mobile browsers, such as MainMobile.vue, ProductListMobile.vue, ProductDetailMobile.vue,
My question is, where and how do I make my SPA render the mobile version of components when viewing in a mobile browser?
Please note that I explicitly want to avoid making my components responsive. I want to keep two separate versions of them.
Thanks,
I have an idea, use a mixin which detects is the browser mobile or desktop (example for js code in this answer ).. then use v-if, for example
so here is an example on https://jsfiddle.net/Ldku0xec/
I was looking for a solution for this and came here but I couldn't find what I needed:
I mixed and matched a few things I read online including answers here so I thought I'd just come back and put all my learnings into one function for anyone else looking:
Usage:
How it works:
Vue Router supports defining the
component
key as a function which returns a promise to support async routes. The most common way being to use the webpackimport()
function which returns a promise. The function which returns the promise is only invoked when the route is about to be rendered ensuring we can lazy load our componentsThe
responsiveRoute
function accepts a map of these functions with keys set for different breakpoints and returns a function which, when invoked, checks the available viewport size and returns invokes the correct promise factory and return's the promise returned by it.Notes:
I like this method because it does not require the application architecture or route configurations to be in a certain way. It's pretty plug and play using Vue Router capabilities provided out of the box. It also does not force you to define a view for every breakpoint-route combination. You can define a route as usual without this(lazy loaded or not) along side other routes that use this without any problems.
This method does not use user agent sniffing but uses the available width of the
document.documentElement
instead. Other methods I saw recommended things likewindow.screen.width
which gives the exact device screen size regardless of the window size or a more robustwindow.innerWidth || document.documentElement.clientWidth || document.body.clientWidth
. Mix and match as needed.My break points are (number and their values) are based on element-ui breakpoints as I used that for normal responsive design. This can again be configured as needed by changing the constants at the top
An extended version of Beaudinn Greves answer:
App.vue:
router.js:
A bit late for this but, in case if any of you are looking for I handled the situation like this: I added meta to my router:
I have a better solution.In src/main.js:
I have simple solution for Vue.js:
And methods: