Incorporating Dynamic Component Imports in Vue.js Data and Computed Properties

I have a component called 'Page' that needs to display another component retrieved via props.

Currently, I am able to successfully load my component by hardcoding the path in the data like this:

<template>
  <div>
    <div v-if="includeHeader">
      <header>
        <fv-header/>
      </header>
    </div>
    <component :is="this.componentDisplayed" />
    <div v-if="includeFooter">
      <footer>
        <fv-complete-footer/>
      </footer>
    </div>
  </div>
</template>

<script>
  import Header from '@/components/Header/Header';
  import CompleteFooter from '@/components/CompleteFooter/CompleteFooter';

  export default {
    name: 'Page',
    props: {
      componentPath: String,
      includeHeader: Boolean,
      includeFooter: Boolean
    },
    data() {
      componentDisplayed: function () {
        const path = '@/components/my_component';
        return imports(path);
      },
    },
    components: {
      'fv-header': Header,
      'fv-complete-footer': CompleteFooter,
    },
  }
</script>

However, I encountered an issue where I couldn't reference my props within the function due to 'this' being undefined.

I attempted to use computed properties instead of data but received an error "Cannot find module '@/components/my_component'". Is there a way to resolve this as I'm still new to vue.js?

computed: {
  componentDisplayed: function () {
    const path = `@/components/${this.componentPath}`;
    return imports(path);
  },
},

I believe there is a solution to this problem, but I may need some guidance as I am still learning Vue.js :)

Answer №1

Instead of attempting to import the component within your child component, import it in the parent component instead and pass the whole component as a prop.

<template>
  <div :is="component" />
</template>

<script>
export default {
  name: "page",
  props: {
    component: {
      required: true
    }
  }
};
</script>

Additionally, in the parent:

<page :component="component" />

and

import Page from './components/Page';

// And further down

data () {
  return {
    component: HelloWorld
  }
}

https://codesandbox.io/s/74649r921x

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

Encountering generator crashes when using Vue Cli remote presets

While attempting to develop a remote Vue CLI preset on GitHub, I encountered a syntax error that I cannot seem to resolve. You can find my preset repository here: https://github.com/christoph-schaeffer/vue-preset The command I entered is as follows: vue ...

What is the most effective method in Vue to transfer data between a child component, its parent, and then the parent's parent?

When working with Vue, what is the most effective way to transfer data from a child component to its parent and then to a higher level parent? Many developers utilize emit to accomplish this task, but is emit truly the best method for passing data through ...

What is the best way to rotate a mesh by 90 degrees in ThreeJS?

Currently, I'm working on rotating a mesh by 90 degrees within Three JS. Below is an image illustrating the current position: My goal is to have the selected mesh rotated parallel to the larger mesh. I attempted to rotate the matrix using the follow ...

Using jQuery, set a restriction on the total number of options in three dropdown menus to

I am currently facing a challenge with 3 dropdowns, each containing 8 options. My aim is to restrict the total selection across all three dropdowns to 8. For instance, if I choose 7 in the first dropdown, I should only be able to pick 1 in the next two. Si ...

obtain data from JSON using JavaScript

Greetings! I am dealing with a JSON output that looks like this: "{ \"max_output_watts\": 150, \"frame_length_inches\": \"62.20\", \"frame_width_inches\": \"31.81\" }" I am using it in a functi ...

Refresh the html of the contenteditable element with the most recent targeted information from the textarea

One issue I'm encountering is quite straightforward: selecting/focusing on a few contenteditable elements, then selecting the textarea and changing the HTML of the last focused element from the textarea. However, my problem arises when the textarea tr ...

"Troubleshooting issue: V-for loop not properly binding data with

Here is my code snippet: <div v-for="item in items"> <div class="background-wrapper" v-bind:style="{ backgroundImage: 'url(' + item.image + ')' }"></div> <h2>{{ item.title }}</h2> </div> Alt ...

What is the best way to access a variable from one JavaScript file in a different file?

Currently, I have a simple cube scene set up in Three.js Now, my goal is to add camera movement using perlin noise. To achieve this, I found and incorporated the Perlin noise library into my project: https://github.com/josephg/noisejs I then included th ...

Will my variables become unbound when a new object is created?

Currently, I am developing a component within my Angular application where I am binding an object: CustomComponent.js angular.module("app").component( "customComponent", { controller: function() { var ctrl = this; ctrl.createInstance ...

Adding a class to a navigation item based on the route path can be achieved by following

I am currently working on a Vue.js project and I have a navigation component with multiple router-links within li elements like the example below <li class="m-menu__item m-menu__item--active" aria-haspopup="true" id="da ...

"Adding a new and unique document to Meteor's MongoDB collection

Currently, I have a simple Tags Collection in Meteor where I check for duplicate Tag documents before inserting: var existingTag = Tags.findOne({name: "userInput"}) If the existingTag is undefined, then I proceed with the insertion. However, I am wonderi ...

"Retrieve the x-coordinate position of a box within a specific div using

https://i.sstatic.net/68yeF.jpg https://i.sstatic.net/ZCrxZ.jpg Is there a way for me to move the box within the gray area? <div id="timeline"> <div cdkDragBoundary="#timeline" ...

Issue: The system is unable to locate the module labeled './lib/binding/napi-v3/argon2.node'

After attempting to install bcrypt or argon2 with the command npm install --ignore-scripts --omit=dev, an error occurred: app-1 | node:internal/modules/cjs/loader:998 app-1 | throw err; app-1 | ^ app-1 | app-1 | Error: Cannot find modul ...

Encountering an endless loop when utilizing cycle-idb with a text field for user input

Struggling to develop a basic test app that captures user input from a text field, displays it, and stores it using cycle-idb. Unfortunately, I've been stuck in an endless loop no matter what steps I take. Below is the complete main function: functi ...

Record the success or failure of a Protractor test case to generate customized reports

Recently, I implemented Protractor testing for our Angular apps at the company and I've been searching for a straightforward method to record the pass/fail status of each scenario in the spec classes. Is there a simple solution for this? Despite my at ...

Convert XML to an HTML table in real-time as new elements are introduced

Currently, I have JSON and AJAX code that fetches XML data every second, which is working smoothly. When I added an XML element, it automatically gets added to an HTML table. The issue arises when I call the function every 3 seconds; the page refreshes due ...

Issue with clicking a button in Selenium using JavaScript for automation

I'm encountering an issue where Selenium is detecting an element as disabled, despite it being enabled. To work around this, I am attempting to click on the element using JavaScript with the following code snippet: IWebElement button = driver.FindEl ...

Is it possible to eliminate process.env.NODE_ENV using browserify/envify?

Currently, I am utilizing ReactJS through NPM and Browserify, but I am encountering difficulties while attempting to build it in production mode as mentioned in the readme. The code I have for setting up browserify is: var browserify = require('brows ...

Executing multiple AJAX calls at the same time in PHP

I have a puzzling question that I can't seem to easily solve the behavior of this situation There are two ajax call functions in my code: execCommand() : used for executing shell commands through PHP shell_exec('ping 127.0.0.1 > ../var/l ...

PHP disregards the starting 202

Currently, I am developing a PHP API Client to interact with an ASP.net (C#) API. By employing the following Javascript function, I am successfully able to retrieve the data: $.ajax({ type: "POST", url: "https://www.eastmidlandstrains.co.uk/s ...