When working with the async setup() method in Vue3 with router-view, I encountered a perplexing issue

After implementing async setup () in Vue 3, I noticed that my component was no longer visible. Searching for a solution led me to this post: why i got blank when use async setup() in Vue3. While the suggested fix resolved the initial issue, I encountered a new problem with a blank page when using the router-view.

<template>
    <div v-if="error">{{error}}</div>
    <Suspense>
        <template #default>
            <router-view></router-view>
        </template>
        <template #fallback>
            <Loading />
        </template>
    </Suspense>
</template>

<script>
import Loading from "./components/Loading"
import { ref, onErrorCaptured } from "vue"

export default {
    name: 'App',
    components: { Loading },
    setup() {
        const error = ref(null)
        onErrorCaptured(e => {
            error.value = e
        })
    }
}
</script>

main.js:

import { createApp } from 'vue'
import router from "./router"
import App from './App.vue'

createApp(App).use(router).mount('#app')

Replacing router-view with one of my custom components displayed the content correctly.

Router:

import { createWebHistory, createRouter } from "vue-router";
import Portfolio from "@/views/Portfolio.vue";
import Blog from "@/views/Blog/Blog.vue";
import Detail from "@/views/Blog/Detail.vue";
import NotFound from "@/views/NotFound.vue";

const routes = [
    {
        path: "/",
        name: "Home",
        component: Portfolio,
    },
    {
        path: "/blog",
        name: "blog",
        component: Blog,
    },
    {
        path: "/blog/:slug",
        name: "detail",
        component: Detail,
    },
    {
        path: "/:catchAll(.*)",
        component: NotFound,
    },
];

const router = createRouter({
    history: createWebHistory(),
    routes,
});


export default router;

Answer №1

<Suspense>'s default setup should incorporate an asynchronous component (specifically, one with async logic()), but instead of that, you have included <router-view>.

To resolve this issue, you will need to restructure the <Suspense> element within its own container component (for example, HomeView.vue) that includes the asynchronous component while leaving the <router-view> in the main App component:

<!-- App.vue -->
<template>
  <router-view />
</template>

<!-- HomeView.vue -->
<template>
  <Suspense>
    <template #default>
      <MyAsyncComponent />
    </template>
    <template #fallback>
      <Loading />
    </template>
  </Suspense>
</template>

Afterwards, make sure to update your router configuration to use the new wrapper component:

const routes = [
  {
    path: '/'
    name: 'Home',
    component: HomeView
  },
  //...
]

Answer №2

Learn how to utilize <Suspense> in conjunction with various components from the Vue documentation.

<RouterView v-slot="{ Component }">
  <template v-if="Component">
    <Transition mode="out-in">
      <KeepAlive>
        <Suspense>
          <!-- main content -->
          <component :is="Component"></component>

          <!-- loading state -->
          <template #fallback>
            Loading...
          </template>
        </Suspense>
      </KeepAlive>
    </Transition>
  </template>
</RouterView>

Reference: https://vuejs.org/guide/built-ins/suspense.html#combining-with-other-components

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Invoking a function through an array within the model where said members are declared

My goal is to consolidate all of my model functionality in one centralized location. I want the ability to access its methods from within the model itself: JavaScript /** * This application displays "OK" a specified number of times based on the button p ...

trouble encountered while parsing JSON information using JavaScript

[ [ { "Id": 1234, "PersonId": 1, "Message": "hiii", "Image": "5_201309091104109.jpg", "Likes": 7, "Status": 1, "OtherId": 3, "Friends": 0 } ], [ { "Id": 201309091100159, "PersonI ...

Can the JQGrid subgrid URL be modified to change the parameter value from "?Id=id"?

I'm currently working on setting up a JqGrid with a subgrid like this... jQuery(document).ready(function() { jQuery("#list").jqGrid({ url: '/OrganizationalUnit/FindAll/', datatype ...

Modifying the name of a file upload in AngularJS

Does anyone know a way to dynamically change the file name in AngularJS? <input type="file" onchange="angular.element(this).scope().filename(this)"> In the filename method, I am attempting to change the file name but the value is not updating. How ...

The combination of select2 and jsonform is not functioning properly

I am having trouble rendering multiple select2 with JSON form. $('#resource-form').jsonForm({ schema: { rest: { type: 'object', properties: { template_id: { type: "array", items: { ...

What are the new coordinates after deformation?

I am dealing with a situation where I have a chart with a rectangle and some points. One point, O, is dependent on the edges of the rectangle. When I drag a corner point, B, the rectangle deforms. Does anyone have suggestions on how I can calculate the n ...

Leveraging ng-class with an Angular $scope attribute

My HTML structure includes: <div class="myDiv"> <div style="width:200px; height:200px;background-image:url('img/200x200/{{largeImg}}.png');" ng-class="{'magictime foolishIn': 1}"> <span> { ...

Three.js dynamic bone animation: bringing your project to life

Can transformations be applied to the bones of a 3D model in three.js to create a dynamic animation? I attempted to move and rotate the bones of a SkinnedMesh, but the mesh did not update. loader = new THREE.JSONLoader(); loader.load(&apos ...

Vue does not consistently update HTML when the reference value changes

I am trying to showcase the readyState of a WebSocket connection by utilizing a Ref<number> property within an object and displaying the Ref in a template. The value of the Ref is modified during WebSocket open and close events. However, I am encount ...

How to prevent click events and still enable scrolling within a DIV using CSS/JS

Basically, I am looking to enable scrolling within a DIV while also disabling click events. Any suggestions on how this can be achieved? Appreciate any help! ...

My project is experiencing issues with the execution of JavaScript codes

Greetings, I'm having trouble with my JavaScript codes. The following code works perfectly: function Choice() { var box = document.getElementById('searchh'); if (!count) { var count = 0; } box.onclick = function () ...

Put emphasis on the input field - React component

My React component features an input field with a disabled attribute. When the component is clicked, the input becomes enabled for the user to type in. I have successfully implemented this functionality so far, but now I need to focus on the input field on ...

Cross-origin resource sharing (CORS) is preventing access because the origin and allowed origin match

Utilizing Dockerized Ory Kratos and Angular (www folder hosted via nginx for header modifications) on localhost and attempting to run the following code: const headers = { Accept: 'application/json', }; fetch('http://127.0.0.1:4433/self-s ...

Saving the selections from two drop-down menus into a single variable

I have a requirement to store the user selected values from two dropdown menus. These dropdowns are created using the selectize library in HTML: <div style="max-width: 200px"> <select id="dropdown-1" ...

Implement VueJS functionality to prevent form submission upon submission and instead submit the form upon keyup

My form has the following structure: <form id="myForm" action="/searchuser" method="POST" @submit.prevent="onSubmit(inputValue)"> <div class="field"> <label class="label">Name</label> <div class="control"> ...

Transform vertical and horizontal scrolling actions into solely horizontal scrolling using HTML and JS

I'm currently working on a unique React.js website that features a horizontal-scrolling portfolio. The website functions as a visual gallery, allowing users to easily scroll through images using their trackpad. Within the website, I have set up a lar ...

Using external VB script (IE automation) to invoke Java Script on a webpage

On a webpage, there is a functionality where a checkbox can be clicked to select all the checkboxes below it. This is accomplished by invoking a JavaScript function on click. However, when attempting to select that checkbox using VBScript with .getElement ...

Invoke a method in a separate class

I am facing issues with passing variables to another file. I have checked my code multiple times but cannot find a solution. It keeps giving me an error in the function. onclick="limit();javascript:AyudaTipos(2)"/> The function is: function limit ( ...

Node React authentication

Struggling with implementing authentication in React Router. I am using componentDidMount to check if the user is logged in by calling an endpoint. If not, it should redirect to login, otherwise proceed to the desired component. However, this setup doesn&a ...