Retrieve a collection of Vue components

My single page website has a simple component structure:

<template>
  <div id="app">
    <header />
    <section-about />
    <section-warranty />
    <section-advantages />
    <section-service />
    <section-review />
    <footer />
    <menu />
  </div>
</template>

Now, I want to populate the menu component with a list of all web page blocks (article sections).

https://i.sstatic.net/jl1INt.jpg

I could manually write this list, but I'm exploring the possibility of parsing my components for a specific key and generating the list automatically. This way, my menu will be dynamically updated as I add or remove article components.

For example, the Warranty.vue component:

<template>
   <section class="article warranty">
      ...blah blah blah...
   </section>
</template>

<script>
export default {
   data() {
      return {
         article-key: 'warranty', // <-- key for parsing
         article-title: 'Warranty'
      }
   }
}
</script>

Similarly, other article components would follow suit...

Next, in my Menu.vue component:

<template>
   <ul class="menu">
      <li v-for="(article, index) in articles" :key="index">
         <a href="#">{{ article.title }}</a>
      </li>
   </ul>
</template>

<script>
export default {
   data() {
      return {
         articles: []
      }
   },
   methods: {
      parseComponents() {
         this.articles = ... <-- iterate through Vue components and return those with an article-key
      }
   },
   created() {
      parseComponents()
   }
}
</script>

Alternatively, should I consider moving all articles to a separate folder? Is there a way to achieve this with Vue?

Answer №1

In the case that you possess all these values stored within this.articles, you have the option to execute the following:

this.articles.forEach(item => {
    if(item.article-key) {
        return <MyComponent/>
    }
})

Answer №2

Create a list of your components:

computed: {
  components() {
    return ['about', 'warranty', 'advantages', 'service', 'review']
  }
}

Display them using this method (https://v2.vuejs.org/v2/api/#is)

<component v-for="component in components" :key="component" :is="component" />

By following this technique, you only need to define your components list once.

To use them in the Menu component - create a prop (https://v2.vuejs.org/v2/api/#props) to pass them as parameters.

Answer №3

I came across a solution that worked for me.

<template>
   <div class="menu">
      <ul class="menu-list">
         <li v-for="(item, index) in items" :key="index">
            <a href="#" @click.prevent="item.el.scrollIntoView({ behavior: 'smooth', block: 'end'})">{{ item.title }}</a>
         </li>
      </ul>
   </div>
</template>

<script>
export default {
   data() {
      return {
         items: []
      }
   },
   mounted() {
      this.items = this.$parent.$children.map(item => {
         return item.$data.itemKey == 'item' ? {
            title: item.$data.itemTitle,
            offsetTop: item.$el.offsetTop,
            el: item.$el
         } : false;
      })
   }
}
</script>

It would be interesting to explore a method for parsing components by their names from an entire folder using regex.

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

Is there a way for me to retrieve the text response of a fetch request from client-side JavaScript to fastify server?

In my fastify node.js application, I am encountering an issue where I can see the text results of a promise right before it is returned to the browser's JavaScript code. However, once the promise is returned to the browser JS, all I get is an empty st ...

Creating a loading spinner in a Vue component while using the POST method

After successfully creating a loader for fetching data using the GET method, I encountered challenges when attempting to do the same with POST method. Is there a reliable way to implement a loader during the POST data process? For GET method, I set the lo ...

Enhance your webpage with a dynamic form feature for adding multiple products using jQuery

I'm currently working on a project to develop a dynamic form that includes both input fields and dropdown menus populated with data from a JSON file (for now, I'm using an array). The form should also have the functionality to "add another produc ...

Click on another part of the page to reveal a dropdown menu

I am seeking a way to trigger the opening of this dropdown select not by directly clicking on its position, but rather by clicking on another <span>. Displayed below is the dropdown menu: <div class="styled-select"> <span id="camDurati ...

Attempting to bring in an image file into a React component

My attempt to add an image at the top of my file failed, so I am looking for help with importing it. The code I originally tried did not work. The image does not display using the code below <img src={require('../../blogPostImages/' + post.bl ...

Is it possible to store Socket.IO responses in a cache for quicker retrieval?

Consider this scenario where I have a websocket implementation shown below: let itemsArray = []; function fetchData() { itemsArray = await db.query(`SELECT * FROM Items`); } function emitData() { io.sockets.in("room_foo").emit("data", JSON.stringify ...

Error encountered in Node.js: Attempting to modify headers after they have already been sent to the client

When attempting to create a login function and sending post requests using Postman, everything works fine with the correct email and password. However, if I try to send the wrong password, I encounter an error message stating that either the email or passw ...

Record of Recaptcha actions is not showing up in the reports

My method of running the recaptcha script is as follows: let data = { action: 'homepage' }; grecaptcha.ready(() => { grecaptcha.execute('RECAPTCHASITEKEY', data).then((token) => { recaptcha_token = token; }); ...

Retrieving a targeted data point from a JSON object

I am working with a json data that contains various properties, but I am only interested in extracting the uniqueIDs. Is there a way to retrieve ONLY the uniqueID values and have them returned to me as a comma separated list, for example: 11111, 22222? (I ...

Is it possible to update the URL dynamically in a Next.js application without relying on the <Link> component?

I'm looking for a way to dynamically change the URL on a page without using <Link>. Specifically, I want to switch to a different URL when a variable changes from false to true, regardless of user interaction. Currently, I'm achieving this ...

Adding the current date and time to a fabric js canvas: a step-by-step guide

Looking to dynamically display the current date and time on a canvas area. The current date and time can be added using an object. However, I am facing an issue where the date and time value does not update continuously. Can anyone suggest how to achieve t ...

AngularJS directive that performs asynchronous validation upon blur

I'm working on developing a directive that validates email addresses provided by users through asynchronous web requests. While the functionality is sound, I've encountered an issue where asynchronous calls are triggered every time a user types a ...

Disable body scrolling on mobile devices in native browsers

When using the native browser on Samsung Galaxy S5 / S6, the following CSS code: body { overflow: hidden; } does not successfully prevent the body from scrolling. Is there a way to work around this issue? Edit: As mentioned below, one workaround is t ...

Exploring front-end AJAX functionality within a WordPress plugin

As a newcomer to WordPress development, I have been working on writing an AJAX request within a WordPress plugin. To test this functionality, I initially sent the request to an external non-WP server where it worked without any issues. Following the guidel ...

Exploring the Method of Accessing data-* Attributes in Vue.js

I have a button that, when clicked, triggers a modal to open. The content displayed in the modal is determined by the data attributes passed to the button. Here is my button: <button class="btn btn-info" data-toggle="modal" data-t ...

Creating a randomly generated array within a Reactjs application

Every time a user clicks a button in reactjs, I want to create a random array of a specific size. The code for generating the array looks like this: const generateArray = (arraySize: number): number[] => { return [...Array(arraySize)].map(() => ~~( ...

What are the best practices for implementing serialization in NestJS?

Recently, I delved into a fresh NestJs project and encountered a hurdle while trying to integrate serialization. The goal was to transform objects before sending them in a network response. Initially, everything seemed to be working smoothly until I attemp ...

Quickly view products in Opencart will automatically close after adding them to the cart and redirecting the

I've integrated the product quickview feature into my OpenCart theme, which opens a product in a popup. However, when I add a product to the cart from the popup, it doesn't update on the main page until I refresh. I'm looking for a way to re ...

Fixing 500 (Internal Server Error) in Vue.js and Laravel: The Ultimate Guide

Working on a university project using Vue.js and Laravel, I need assistance with sending information to the API. I'm trying to use axios for the POST request, but it's giving me an error: 500 (Internal Server Error). I can't seem to identif ...

Ways to properly release file descriptors in write streams

I'm currently working on a code snippet that showcases what I'm aiming to achieve: const fs = require('fs'); var stream = fs.createWriteStream('/tmp/file'); stream.once('open', function(fd) { for (var i = 0; i ...