Having trouble loading a lazy component in Vue3 with v-if condition?

The code is quite simple. However, I am facing an issue where the about component cannot be rendered.

<template>
  <div id="nav">
    <button @click="sh = !sh">{{ sh }}</button>
    <p v-if="sh">v-if</p>
    <about v-if="sh" />
  </div>
</template>
<script lang="ts">
import { defineComponent, ref } from "vue";
export default defineComponent({
  components: {
    about: () => import("@/views/About.vue")
  },
  setup() {
    const sh = ref(false);
    return {
      sh
    };
  }
  // data: () => ({
  //   sh: false
  // })
});
</script>

I have tested this in a vue2 project using JS and vue2.6.11, and everything seems to work fine as usual.

Do you think it could be a bug or am I missing something? Your input would be greatly appreciated. Thank you.

Answer №1

Definitely! However, it is important to declare the lazy component in the following manner.

about: () => defineAsyncComponent(() => import("@/views/About.vue")) // incorrect way
<template>
  <div id="nav">
    <button @click="sh = !sh">{{ sh }}</button>
    <p v-if="sh">v-if</p>
    <about v-if="sh" />
  </div>
</template>
<script lang="ts">
import { defineAsyncComponent, defineComponent } from "vue";
// Alternatively, lazy components can be declared here as well
//const about = defineAsyncComponent(() => import("@/views/About.vue"));
export default defineComponent({
  components: {
    about: defineAsyncComponent(() => import("@/views/About.vue"))
  },
  data: () => ({ sh: false })
});
</script>

Answer №2

<template>
 <div>
    <h1>Hello World!</h1>
    <component :is="name"/>
    <button @click="onClick">Click me !</button>
 </div>
</template>
<script>
import { defineAsyncComponent, defineComponent, ref, reactive, computed } from "vue"

export default defineComponent({
  name: 'MyApp',
    components: {           
      section: defineAsyncComponent(() => import("../views/Section.vue")),
    },
    data: () => ({
      cardItems: [],
            show: false
    }),
    setup () {
      const display = ref(false);
      const dynamicComponent = computed (() => display.value ? defineAsyncComponent(() => import("../views/AddItem.vue")) : '')

      const onClick = () => {
          display.value = !display.value;
      }               
       
      return {          
          onClick,
          dynamicComponent,
          display
      }
  }
})
</script>

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

Guide on implementing a template within a form using Vue.js

I have set up a Vue instance for handling the form data var formInstance = new Vue({ el: '#amount_form', data: { logdate: '', amount:'', description:'' }, methods: { ...

In JavaScript, what do we call the paradigm where a variable equals a variable equals a function? Let's take

Feeling a bit overloaded at the moment, so forgive me if this question seems too simple. I managed to accidentally write some code in Jest for testing a Vue application that actually works: const updateMethod = wrapper.vm.updateMethod = jest.fn() expect(u ...

What steps are involved in generating a Typescript module definition for a directory containing a babel-plugin-content-transformer?

Currently utilizing the babel-plugin-content-transformer to import a directory containing YAML documents in a React Native/Expo project. The configuration for my babel plugin looks like this: ['content-transformer', { transformers: [{ ...

Encountering Invalid Chai attribute: 'calledWith'

I am currently in the process of implementing unit tests for my express application. However, I encountered an error when running the test: import * as timestamp from './timestamp' import chai, { expect } from 'chai' import sinonChai f ...

What is the reason for recursion not producing a new object as output?

Trying to filter out nodes in a recursion function that iterates through a tree based on the registry property. function reduceNodesRegistry(source: any) { if (!source.registry) return source; return { ...source, children: s ...

Ensure that all files with the extension ".ts" take precedence and are imported

I am facing an issue with my component as I have two files associated with it: app/components/SomeButton.ts app/components/SomeButton.tsx The .ts file contains most of the logic and code, while the .tsx file extends the .ts and only contains the ren ...

"Exploring the process of integrating a new language into the vuejs3-datepicker feature

Hey there, I'm wondering if anyone knows how to integrate a new custom language into vuejs3-datepicker? I checked out the documentation at https://www.npmjs.com/package/vuejs3-datepicker?activeTab=readme, but it seems like you need to add the new lan ...

Using Laravel Blade, import a Vue.js component directly into your file

After registering some components as global components in the js/app.js file, it has resulted in the compiled app.js file becoming larger. //example: app.js Vue.component('profile-page', require('./components/profiles/ProfilePage.vue') ...

Master the art of utilizing watchers and computed properties for intricate computations

Here's the scenario I'm dealing with: The user is able to enter Working hours and expenses, From these inputs, a calculation needs to be performed to determine the final value, with both vat and payrate being pre-defined constants. pay_amount ...

generating declaration files for components with accurate type definitions from propTypes

I am in the process of creating a react/js library using rollup. My approach involves utilizing typescript to generate declaration files for my components. Despite having propTypes defined for my components, I have noticed that the emitted .d.ts files as ...

Formula for determining the slider's span

I recently created a range slider using Vue.js It has a minimum and maximum value, assumed to be percentages as it ranges from 0 to 100. My goal is to set the minimum value at $5,000 and the maximum at $200,000, However, I struggle with math and need th ...

How can I transfer checkbox selections from a dynamically generated table row to an Array in Vue?

After retrieving data from the Database, I pass it to the <tbody> element by iterating through its rows. These rows are enclosed within a child component and imported into the <tbody>: <template> <tr> <td> ...

Bringing in information from a TypeScript document

I'm having trouble importing an object from one TypeScript file to another. Here is the code I am working with: import mongoose from "mongoose"; import Note from './models/notes'; import User from './models/users'; import ...

Update the image path in Vue depending on the size of the screen

I'm looking to dynamically change the image src based on screen size in my Nuxt project. The current code I have is as follows: <div v-for="(item, index) in aside" :key="index""> <img :src="item.svgIconDark.fi ...

What is the process for including an item in an array within Firestore?

Can someone help me with this code snippet I'm working on: await firebase.firestore().doc(`documents/${documentData.id}`).update({ predictionHistory: firebase.firestore.FieldValue.arrayUnion(...[predictions]) }); The predictions variable is an ar ...

Developing components through JavaScript

I am attempting to use JavaScript to create an element in my HTML using createElement, but there seems to be an issue in my code. HTML <button class="test_button">I am a test</button> <div class="test"></div> ...

Stopping Vue Router from re-rendering the page: Is it possible?

I am having an issue with my News.vue and News-View.vue. Whenever I navigate to news/1, it directs me to the News-View.vue page. The problem arises when there are multiple search filters (such as category, date, etc.) and infinite scroll implemented in the ...

Integrating Typescript into function parameters

I am attempting to make my function flexible by allowing it to accept either a string or a custom type onPress: (value: string | CustomType)=>void But when I try to assign a string or CustomType, the compiler gives an error saying is not assignable to ...

Encountering incorrect month while utilizing the new Date() object

My Objective: I am looking to instantiate a new Date object. Snippet of My Code: checkDates (currentRecSec: RecommendedSection){ var currActiveFrom = new Date(currentRecSec.activeFrom.year,currentRecSec.activeFrom.month,currentRecSec.activeFrom.day ...

What is the best way to organize nestedGroups in the vis.js timeline?

Running into an issue with the nestedGroups in my code. Despite sorting the array before creating the items and nestedGroups, I'm encountering a problem where the first item is showing up in the last position on the timeline. Attached is a screenshot ...