"Utilizing VueJS XHR functionality within a versatile and reusable component

Seeking advice on best practices for improving the following scenario:

I have a single global reusable component called <MainMenu>. Within this component, I am making an XHR request to fetch menu items.

If I place <MainMenu> in both the header and footer, the XHR request will be sent twice.

Alternatively, I could use props to retrieve menu items in the main parent component and then pass them to <MainMenu> like so:

<MainMenu :items="items">

However, this approach may limit quick reusability in other projects as I would need to pass props each time.

Another option is to utilize state, which is essentially similar to props.

What would be the best course of action for this particular use case?

Answer №1

If you prefer not to create a new component each time, but want your main menu to appear in multiple locations, you can utilize the ref="menu" attribute to access its content through innerHTML or outerHTML. An example demonstrating this can be found here.

<div id="app">
  <main-menu ref="menu" />
  <div v-html="menuHTML"></div>
</div>

It's important to note that refs are not reactive, so attempting to use

v-html="$refs.menu.$el.outerHTML"
directly may lead to errors. To properly display the menu's content, you need to initialize it in the mounted hook:

data() {
  return {
    menuHTML: ''
  }
},
mounted() {
  this.menuHTML = this.$refs.menu.$el.outerHTML;
}

This approach allows for displaying the menu in various places without creating new components, although it lacks reactivity.

In the provided example, menu items are stored in an items array. Any changes made to objects within this array will affect the main component but not its clones. For instance, I demonstrate adding the "red" class to items after a delay of two seconds.

To ensure changes reflect on cloned elements as well, you should set up a watcher to monitor modifications in the items array and update the menuHTML accordingly:

mounted() {
  this.menuHTML = this.$refs.menu.$el.outerHTML;
  this.$watch(
    () => {
        return this.$refs.menu.items
    },
    (val) => {
      this.menuHTML = this.$refs.menu.$el.outerHTML;
    }, {
    deep: true
    }
  )
}

You can also keep track of changes in any data property using:

this.$refs.menu._data

By following this method, you can avoid passing props to the main menu component or making alterations to it directly. However, implementing additional logic in the parent component is necessary for this solution to work effectively.

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

Using a single Angular component to dynamically load data based on the query string

I am curious if it is feasible to load data based on a query string. For instance, when the user clicks on the following link http://localhost:4200/earning/customers?type=archived, the data will be loaded using the same component CustomersComponent. Simila ...

C# web service is unable to return a specific value

I attempted to use a basic web service (just to test if the value will populate in the JavaScript code). I experimented with a very simple snippet, but it kept returning 'undefined'. Can you offer some guidance? I have tried several solutions wit ...

The webpage is missing a rendered React component even though it should be displayed

I am facing an issue where a React component is not appearing on the webpage despite being rendered. I have provided the code and screenshots of the components below for reference. Below is the snippet from the "App.jsx" file: function createCard ...

How can constants from components be defined in multiple ways when imported? (specifically in React)

Although I have a good understanding of React and Javascript, I struggle to articulate my question effectively. I will provide examples in the hopes that someone with more expertise in the field can assist me. For instance, when using import { useRef, use ...

A guide to parsing JSON files and extracting information

How can I extract the name and status from a JSON object? I've attempted various methods like [0] - [1], as well as trying without, but to no avail. [ { "status": "OK" }, { "id": "1" ...

A guide on testing mouse clientY in React using JEST for effective testing

useEffect(() => { const mouseHandler = (event: MouseEvent) => { menuData.forEach((element) => { if (element.hasActiveDropdown && event.clientY > 50) { handleCloseDropDown(); // handleDropDown('0') ...

Restangular failing to apply headers during post requests

I have been encountering an issue while trying to set the header for a single post request using Restangular. Despite following the documentation here and seeking help from a similar question, the request is being sent as plain text instead of JSON. My se ...

Causing a click event to occur results in crashing the browser

Take a look at this link: example on jsfiddle Why does the click event keep triggering multiple times when a div is clicked, eventually causing the browser to crash? What could be causing this issue and how can it be resolved? The actual div contains a l ...

Some packages seem to be missing in React Native

I decided to incorporate a project I cloned from GitHub into my React Native app by placing it in a separate folder outside of the app. After running npm link on the project and linking it to my own project, I encountered an issue when attempting to run i ...

Is there a way to showcase the generated results on a graph after the user presses the submit button?

I've been working with to generate a bar chart. Currently, when the user clicks 'submit', the input numbers are shown in a graph on http://jsfiddle.net/jx9sJ/5/. Now, I want to make some changes. I am attempting to send the input numbers t ...

Tips for setting up a full-size image with nextJS and the <Image /> component

Upgrading NextJS to the latest version has resulted in some errors when using the Image component: // import Image from 'next/image' <div style={Object.assign({}, styles.slide, style)} key={key}> <Image src={src} alt="&quo ...

Changing the Month Label Format from Short (MMM) to Long (MMMM) in Angular Material Datepicker

I am looking to customize the month labels in Angular Material datepicker. By default, the month view displays in MMM format and I want to change it to MMMM using custom MatDateFormats. export const APP_DATE_FORMATS: MatDateFormats = { parse: { dat ...

Monitoring changes in an array of objects using AngularJS's $watch function

Exploring the world of AngularJS, I'm on a quest to solve a challenging issue efficiently. Imagine having an array of objects like this: var list = [ {listprice: 100, salesprice:100, discount:0}, {listprice: 200, salesprice:200, discount:0}, {listpr ...

What is the best way to retrieve the value of an input field in React when incorporating Material UI components?

I am working with a few radio input components that have been imported from material Ui react. Each radio input is wrapped in a FormControlLabel component. <FormControlLabel onClick={checkAnswerHandler} value={answer} control={<Radio color=&quo ...

Count the number of distinct values in an array of objects

Could you assist me with a JavaScript problem I'm experiencing? I have an array and need to extract the count key from the response. Here is a sample response: var events = [ ... I would like the array response to look like this: var events = [ ... ...

Images are not displaying on Vue Canvas

I am in the process of creating a design using a canvas and six different images. Here is an example of my template: <div> <img id="right_arm" src="../assets/body_parts/right_arm.png" style="display:none;" alt=""> <img ...

Problem with Clerk's authentication() functionality

Currently facing an issue with the Clerk auth() helper (auth() documentation) while working with react and next 13 (app router). When trying to access both userId and user from auth(), const { userId, user } = auth();, it seems that userId contains a val ...

Updating an image using AJAX and Flask

I have a situation in HTML where I need to constantly update an image file with the latest images that come in. Below is the Flask code snippet: @app.route('/uploads/update_file', methods=['GET', 'POST']) def update_file(): ...

Lighthouse Issue: Facing PWA Challenges with a "Request Blocked by DevTools" Error

For hours now, I've been struggling to make Lighthouse work in Chrome for my initial PWA project. I feel completely lost as nothing seems to be making sense despite the basic code I have included below. The issue arises when I load the page normally ...

What is the best way to rotate a cube when it is clicked on?

My current project involves rotating a cube by clicking on buttons either on the cube itself or floating next to it. At the moment, I have them floating for easier testing purposes, but placing them directly on the cube is not an issue. The main issue I&a ...