"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

AJAX function in Chrome console is throwing an error message stating "Unexpected Token }"

Dealing with this issue has been quite unusual for me. I've spent the last 3 days trying to troubleshoot it, but now it's no longer bothering me. The situation involves a button and a textbox that sends the data from the textbox to a PHP page whe ...

"Enhance your web development skills by mastering jQuery alongside the

It's curious that jQuery doesn't support the use of the "+" sign. You can see how it functions with "1" and "3", but not with "2+". Just hover your mouse over each div to experience it. <div id="div-2+"></div> JSFiddle $('a. ...

What could be causing the array to display incorrect results in React?

Showing below is a snapshot of my VScode. In this code snippet, I am declaring arr1 as an array consisting of numbers and then performing a reverse operation on it. Click here for input. The issue I am encountering is that the first paragraph in the outpu ...

Angular HTTP requests are failing to function properly, although they are successful when made through Postman

I am attempting to send an HTTP GET request using the specified URL: private materialsAPI='https://localhost:5001/api/material'; setPrice(id: any, price: any): Observable<any> { const url = `${this.materialsURL}/${id}/price/${price}`; ...

Dropdown Placement Based on Button Click

Looking to create an interactive dropdown menu with the Alloy UI Dropdown Component that appears when a user clicks on one of four buttons. The goal is for this dropdown to be positioned to the left of the clicked button. var toolsDropdown = new Y.Dropdow ...

What is the best way to redirect a user to a different URL in Express while also sending additional data along with the request

[NODE, express] Developing a Facebook application where user grants access and is redirected to my site with a unique code at abc.com/heyBuddy/fb/callback?code="adasdasdasda". Once the code is received in route router.get('/heyBuddy/fb/callback', ...

Issue with React app: IconMenu does not expand when clicked

Seeking assistance with a react app and IconMenu from material-ui. I've been researching similar issues extensively but haven't found a solution yet :( In the code below, I am looking to manually trigger the expansion of a menu - this is essenti ...

Why does Typescript not enforce a specific return type for my function?

In my custom Factory function, I need to return a specific type: type Factory<T> = () => T; interface Widget { creationTime: number; } const createWidget: Factory<Widget> = () => { return { creationTime: Date.now(), foo: &a ...

The result of filtering multiple data using checkboxes in Vuetify is not displaying as expected

I am currently working on developing a straightforward task scheduler that includes filtering options using checkboxes. Below is the snippet from my vue file: Within my templates section, <fieldset> <legend>TASK STATUS</legend> ...

Can you explain the distinction between the GenerateSW and InjectManifest choices within the vue ui pwd configuration?

Currently utilizing @vue/cli for building a vue project. I have initiated vue ui to access the vue UI and am in the process of customizing various available options. https://i.sstatic.net/h77AE.png Within Configuration -> PWA, I have come across the a ...

Save all user information annually from the date they first sign up

Greetings! I am facing an issue where every time a year is added, it gets inserted between the day and month in the date of entry for a user at our company. var yearOnCompany = moment(user.fecha_ingreso_empresa, "YYYYMMDD").fromNow(); var dateStart = mome ...

The combination of React and Redux with the utilization of combined reducers

Hey there, I'm currently utilizing thunks to retrieve data from my backend, but I'm a bit uncertain on how to implement it in my combined reducer. Here are my types: export const FETCH_SUCCESS = 'FETCH_SUCCESS'; export const FETCH_FAI ...

Is there a way to divide all the characters within a string, excluding the sequence " "?

My issue (resolved) I've been working on an animation where each letter appears sequentially, but I encountered a problem. In order to transform the letters properly, I had to wrap my span tags in a flex div because using inline-block didn't all ...

Is there a way to slow down the falling effect on my navigation bar?

As I was working on my personal website, I had a creative idea to add a falling-down animated effect instead of keeping the layout fixed. Utilizing bootstrap for navigation, I encountered some difficulty in controlling the speed of the falling effect. Any ...

Is it possible to transfer an HTML table to a PowerPoint presentation directly from the client

Is there a specific jquery or javascript solution available for converting an HTML table directly into a PowerPoint presentation? So far, the only solution I have come across is html table export, which provides export options for various file formats. H ...

How can I best fill the HTML using React?

After attempting to follow various React tutorials, I utilized an API to fetch my data. Unfortunately, the method I used doesn't seem to be very efficient and the code examples I found didn't work for me. I am feeling quite lost on how to proper ...

What could be causing the issue of loading text not appearing in Vue.js?

I have the following code snippet in my application: <div id="app"> <button v-if="!isPrepared && !isLoading" @click="startLoading()">Start Loading</button> <div v-if="isLoading">Lo ...

What methods can I employ with JavaScript to catalog data collected from an HTML form?

Currently, my form requires users to input a username that cannot start or end with a period (.). I have implemented some code but I believe there is an issue with the .value[0] parts. //Checking Username if (document.getElementById("uName&quo ...

Connecting the SignalR client to various servers

I am currently incorporating SignalR version 2.x into my ASP.Net MVC application, which is also using the same version of SignalR in my Angular client app. The ASP.Net MVC application is hosted at http://localhost:42080, while the Angular app is hosted at ...

Maintain the previous droppable positioning after refreshing the page

I am encountering an issue with the .droppable event. I have set up two sections where I can move elements, but every time the page is refreshed, the positioning of the elements reverts to the initial position. How can I maintain the last positioning of th ...