Home > OS >  Exporting error: Modifiers cannot appear here
Exporting error: Modifiers cannot appear here

Time:01-09

App.vue

<template>
  <MNavbar v-if="mobile"/>
  <Navbar v-else/>
  <RouterView/>
</template>

<script setup lang="ts">
import { RouterView } from 'vue-router';
import Navbar from './components/Navbar.vue';
import MNavbar from './components/MNavbar';


if (/Android|iPhone|Opera Mini/i.test(navigator.userAgent)) {
  export var mobile=true;
}

else() {
  export var mobile=false;
}

</script>

I am trying to render a mobile variation whenever it detects if it's just these types of mobile devices but for some reason I can't export the mobile variable. "Modifiers can't appear here" error. New to coding and stack overflow so any help is appreciated! Don't hesitate to ask for more info or to critique a bad practice (or if you have any different alternatives). MNavbar is the mobile navbar I am trying to render when the conditional is true.

I attempted 2 v-if statements for MNavbar and Navbar but that didn't work so I tried v-if and v-else which worked. I'm sure I'm just missing something regarding my exports.

CodePudding user response:

I think you get the error from typescript because you are trying to access navigator while the DOM is not available yet. Try wrapping it in a onMounted lifecycle hook.

Also, you need to define your mobile variable in a different way. I think you need to make that reactive, by using ref. To prevent the non-mobile navbar from flashing on the mobile screen, you can use a loading variable and v-if.

So you would get something like this (untested code):

<template>
  <template v-if="!loading">
     <MNavbar v-if="mobile" />
     <Navbar v-else />
     <RouterView/>
  </template>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { RouterView } from 'vue-router';
import Navbar from './components/Navbar.vue';
import MNavbar from './components/MNavbar';

const mobile = ref(false);
const loading = ref(true);

onMounted(() => {

   if (/Android|iPhone|Opera Mini/i.test(navigator.userAgent)) {
        mobile.value = true;
   }

   loading.value = false;
})

</script>

CodePudding user response:

I realized I complicated the issue much more than I should have. I instead used CSS media queries to fix the issue.

Instead of typescript I queried

@media screen and (max-width: 1096px)

and disabled the desktop nav/homeview with

display: none;

Updated code below:

@media screen and (max-width: 1096px){
  #homeview{
    display: none;
  }
  #navbar{
    display: none;
  }
}

This will allow screens with less than 1096px to not see the desktop version.

  • Related