1

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 class="bg-white shadow" 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)

1 Answer 1

2

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...
 */

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.