Home > Blockchain >  Vue router router-view not working when add beforeEach in Vue's main file
Vue router router-view not working when add beforeEach in Vue's main file

Time:09-23

When I add beforeEach method inside router constant the App.vue route stop working:

main.ts:

import { createApp } from 'vue'
import './tailwind.css'
import App from './App.vue'
import { createRouter, createWebHistory } from 'vue-router/auto'
import { createHead } from '@vueuse/head'

const app = createApp(App)
const head = createHead()



const router = createRouter({
  history: createWebHistory(),
}).beforeEach((to, from, next) => {
  const publicPages = ['/'];
  const authRequired = !publicPages.includes(to.path);
  const loggedIn = !!sessionStorage.getItem('Orcamento:token');

  if (authRequired && !loggedIn) {
    next('/login');
  } else {
    next();
  }
});

app.use(router)
app.use(head)
app.mount(document.body)

App.vue:

<script setup lang="ts">
import { computed } from "vue";
import useProject from '../src/stores/index';

const project = useProject();
const loggedIn = computed(() => project.status.loggedIn);

</script>

<template>
  <navbar v-if="loggedIn" />
  <div>
    <header  v-if="$route.meta.title">
      <div></div>
    </header>
    <main>
      <router-view />
    </main>
  </div>
</template>

I'm using Vue 3 and the devDependecy unplugin-vue-router

Errors messages:

[Vue warn]: Failed to resolve component: router-view If this is a native custom element, make sure to exclude it from component resolution via compilerOptions.isCustomElement. at <App>

[Vue warn]: Property "$route" was accessed during render but is not defined on instance. at <App>

[Vue warn]: Unhandled error during execution of render function at <App>

Uncaught TypeError: Cannot read properties of undefined (reading 'meta') at Proxy._sfc_render (App.vue:19:9)

CodePudding user response:

The problem is createRouter() returns a router, but beforeEach() does not.

So when you're doing

// incorrect ❌

const router = createRouter().beforeEach();

router ends up being undefined, because it's assigned the value returned by beforeEach, instead of being assigned the value returned by createRouter.

A more verbose way of writing the above code:

// incorrect ❌

let router = createRouter();
router = router.beforeEach();

// router is now `undefined`

To correctly assign the router to router:

// correct ✅

const router = createRouter();
router.beforeEach();

/* 
 * here router is still the returned value of `createRouter()`, 
 * so it can be exported, used in the app, etc...
 */

  • Related