0👍
If you have the ability, I would recommend using Device module which does the middleware stuff you are trying to do automatically.
On your question. This isn’t how you define middleware in nuxt 3.
You use defineNuxtRouteMiddleware((to, from) => {...})
for that.
I would first define a middleware like this.
export default defineNuxtRouteMiddleware((to, from) => {
let userAgent = process.server
? useRequestHeaders()["user-agent"]
: navigator.userAgent
to.params.isMobile = String(/mobile/i.test(userAgent))
})
And then access the isMobile parameter in the page file like this.
<script setup lang="ts">
const layout = useRoute().params.isMobile == "true" ? "mobile" : "desktop"
</script>
<template>
<NuxtLayout :name="layout">
whatever
</NuxtLayout>
</template>
Now, I wouldn’t recommend the second option. + I would use a reactive value rather than untyped isMobile parameter. + I wouldn’t put this logic in every page, but in the layout itself
- [Vuejs]-How to add an icon inside the vue child component?
- [Vuejs]-Laravel 10 with vue doesn't work for me, the app.js file can't find it
Source:stackexchange.com