Implementing Vue component loading asynchronously upon user click

I'm currently working on creating a component with nested components in Vue. The structure can be simplified as

ParentComponent.vue
|
|__ ChildComponent.vue

My goal is to load the ChildComponent only when a button is clicked using @click in the ParentComponent. I want the component to fetch its files dynamically after the click event, rather than just toggling visibility. This approach will help optimize network usage especially considering potential deep nesting.

UPDATE: I attempted the following code snippet

<template>
  <div class="home">
    <button type="button" @click="isActive=!isActive">SHOW</button>
    <async-component v-show="isActive"></async-component>
  </div>
</template>

<script>

const AsyncComponent = () => ({
  // The component to load (should be a Promise)
  component: import('./components/ChildComponent.vue'),
  // A component to use while the async component is loading
  loading: LoadingComponent,
  // A component to use if the load fails
  error: ErrorComponent,
  // Delay before showing the loading component. Default: 200ms.
  delay: 200,
  // The error component will be displayed if a timeout is
  // provided and exceeded. Default: Infinity.
  timeout: 3000
})

export default {
  name: "home",
  components: {
    AsyncComponent
  },
  data(){
    return{
      isActive:false
    }
  }
};
</script>

However, upon clicking the button, the component appears without any network requests being made based on the developer tools network tab. It seems that the component is pre-loaded instead of dynamically fetching it, as intended.

Answer №1

Commentary points out the article as a valuable resource, emphasizing a crucial aspect.

For Browserify users seeking to incorporate async components, it's worth noting that the tool's creator has explicitly stated that asynchronous loading is not on Browserify's roadmap. However, the Browserify community has devised some workarounds suitable for intricate and established applications. In cases outside of these parameters, consider utilizing Webpack for seamless support of asynchronous operations.

In summary, if you are using Browserify, which seems likely given your Single File Components usage, implementing async components may pose a challenge.

Addtionally, with your use of v-show, employing a display class set to hidden will load the element by default even without Browserify. Opt for 'v-if' instead, which toggles elements by adding or removing them, rather than just adjusting visibility (validate this through the debug console).

An alternative approach could be code-splitting, where Browserify divides the component into a distinct file. However, this method may not yield the desired outcome.

Here's an illustration:

const Menu = () => import(/* webpackChunkName: "signed-in" */ './pages/Menu');

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

NodeJS authentication using Express-Session and Passport encounters errors

I have successfully implemented authentication and login functionality using the Google OAuth API in my NodeJS backend. const passport = require('passport'); const GoogleStrategy = require('passport-google-oauth').OAuth2Strategy; ...

Prevent methods from being called in a Typescript class after they have already

I encountered a scenario where I need to exclude certain methods from the return type of a class method once they have been called. Consider a class named Setup with methods step1, step2, and step3. class Setup { step1() { return this; } ...

Invoke a function that generates an array within a v-for loop and iterate through the elements in a Vue.js component

Seeking guidance on the optimal approach for this task. I need to invoke a method within a v-for loop that lazily loads data from a related model. Can anyone advise on the best practice for achieving this? <div v-for="speaker in allSpeaker" :k ...

Is there a way to retrieve the ID following the creation of a MySQL row in Vue and Express?

I have a query regarding retrieving the ID from Sequelize.create. I have a database called Cases where all cases created by users are stored. Additionally, there is a database named CasesImages that stores images related to these cases. Case model: module ...

Utilizing Async/Await with Node.js and Mongoose

Learning Promises and async/await programming is a new challenge for me, especially in the context of creating an API using Nodejs, Express, Mongoose, and MongoDB. While most tutorials focus on handling asynchronicity within a single file containing routin ...

Submitting forms with Ajax in IE(8)

Sample Google form Related spreadsheet I modified the original code to create two custom forms: First created form Second created form Both forms are functional on most browsers except for IE(8). Any idea why? First form: <!DOCTYPE html> <h ...

Which is the better choice for implementing a singleton: let or var?

I have a clear understanding of the distinction between let (locks the reference inside the block) and var (declares a variable accessible scope-wide). When it comes to implementing the singleton pattern in a module-based setting: var singleton = null; m ...

Is there a way I can display various images and texts, such as testimonials, in a scrolling format

Hi there, I'm looking for some assistance. Currently, I have a block of code that displays an image and text for testimonials on my website. I would like to showcase 6 testimonials with 2 displaying at a time for a few seconds before transitioning to ...

How can I personalize pagination with the reactable library?

As I work on implementing pagination for a reactable table, I have referred to the documentation which clearly outlines how to add this functionality using itemsPerPage and pageButtonLimit: <Table className="table" data={[ { Name: 'Griffin Smi ...

Exploring the usage of multidimensional arrays in React components

How can I extract data such as teamId from the "teams" array using datas.map() method in a multidimensional array? Any tips or help would be appreciated. Is there another way to map out this data? { "gameId": 3226262256, "platformId": "NA1", " ...

Using three.js to integrate an image onto the ground within a panorama

I need help with adding a small image (256x256) to the floor of the Panorama code I am using. Can anyone provide guidance on how to accomplish this task? ...

browsing and extracting information from JSON datasets

Currently, I am utilizing ajax to fetch a json string from the server and then employing eval to convert it into an object. However, when I loop through the data obtained from the json, only the key is displayed. Is there a way to extract the value associa ...

"Modifying Code Aesthetics in WebStorm/IDEA: A Step-by-

Here is the code style I am currently using in my JavaScript project: var obj = { a: 1 , b: 2 , c: 3 } var arr = [ 'a1' , 'a2' , 'a3' ] const w = 1 , w2 = 2 , w3 = 3 The team claims they are following npm's co ...

Develop a dynamic thunk and additional reducer to efficiently handle multiple API calls and retrieve data

Using Redux and Redux-Toolkit, I aim to streamline my code by implementing a single asynchronous Thunk and extra reducer for multiple requests. Below is the setup for both the company and client slices: import { createSlice, createAsyncThunk } from &apos ...

What is the best method to extract and manipulate data from a JSON file in an AngularJS application?

personManagerInstance.getString("firstname",'common','en') I am currently passing a direct string in the UI which is affecting it. What I actually need is to read the data from a JSON file and return it as a string. personManagerInstan ...

Express.static is having difficulty serving the JSON file

I have a series of inquiries: Currently, I am in the process of developing an application using Angular and Node (Express). 1) Within my Node server, I am serving all static files from my 'static_dir' app.use(express.static(STATIC_DIR)); Insi ...

Activate Mixitup Filters Automatically When Page Loads

I have integrated the Mixitup utility from into my ExpressionEngine website. The purpose of this integration is to filter a listing of real estate properties by region, features, and other criteria. My goal is to allow users to pass values via URL segmen ...

Tips on displaying the menu only when scrolling through the webpage

Currently, my website has a right menu that causes overlap with the content on mobile and small devices. To address this issue, I am working on hiding the right menu when the page is stable. The plan is for the menu to appear as soon as the user starts sc ...

Adjustable Columns in Bootstrap Table

After searching, I came across this documentation on how to make columns resizable in bootstrap tables. However, I am struggling to figure out how to actually implement this feature with an HTML table. Can someone please provide a clear example of how to ...

Is there a way to prevent pixels from being rendered outside of a designated rectangle in HTML5?

I'm looking to add screen-in-screen functionality to my HTML5 game, and I have an idea for how to approach it: //Function called every frame function draw(){ set a mask rectangle only draw pixels from the current frame that fall within this recta ...