To understand
The official website, need to consider SEO, using nuxt.js SSR development. The PC and mobile terminals are separated, which is equivalent to two independent projects deployed on the same server and bound to different domain names.
The problem
To determine the current device, switch to each other before the two ends.
To solve
Check whether it is a mobile device based on the UA of the browser:
let isMobile = (ua) => {
return!!!!! ua.match(/AppleWebKit.*Mobile.*/) }Copy the code
Because I haven’t been in touch with Nuxt.js for a long time, and I don’t think I can go deep. Go with your gut:
Mounted in default.vue
mounted() {if(process.browser){
let ua = navigator.userAgent
letisMobile = isMobile(ua) ... window.location.href = ... }}Copy the code
Of course, this is possible, but the problems are numerous:
- The jump time is relatively long (in
mounted
The previous data has been requested and the page has been rendered, so it takes a long time. - Sometimes it doesn’t work (not sure why)
Updated version 2: Moved this operation to the updated version of default.vue, but seems to have no effect.
Version 3: Use Middleware
For Middleware, the introduction to the website:
Middleware allows you to define a custom function to run before a page or set of pages are rendered.
Middleware execution flow sequence:
- nuxt.config.js
- Match the layout
- Matching page
Okay, new midd.js under middleware:
export default function ({ isServer, req, redirect, route }) {
let pcOrigin = 'http://localhost:3003'
let mobileOrigin = 'http://localhost:3004'
let isMobile = (ua) => {
return!!!!! ua.match(/AppleWebKit.*Mobile.*/) }let userAgent = req ? req.headers['user-agent'] : navigator.userAgent || ' '
return isMobile(userAgent) ? ' ': redirect(pcOrigin + route.fullpath) // Use redirect to redirect to external chains with prefix: HTTP/HTTPS}Copy the code
Then add the corresponding configuration to nuxt.config.js:
router: {
middleware: 'midd'
},
Copy the code
In this case, midd.js will be called before each page is rendered. If you do not need to judge every page, you can write in the page that needs to judge the jump, and then remove the nuxt.config.js.
I tested it, and it worked pretty well. The response is very fast.
Another untried idea is to write the jump as plugin and mount it in nuxt.config.js. (PS: Thought of during writing)
end