Leveraging various routes to access data with a shared VueJS 3 component

Could you please review this code snippet: It displays two routes that utilize the same component to fetch content from an API.

Main.js

const router = createRouter({
    history: createWebHistory(),
    routes: [
        {
            path: "/route1",
            name: "Route1",
            component: BaseContent,
            meta: {
                title: 'Route 1'
            }
        },
        {
            path: "/route2",
            name: "Route2",
            component: BaseContent,
            meta: {
                title: 'Route2'
            }
        }
    ]
});

BaseContent.vue

  <base-section v-for="entry in this.entries" :key="entry" lang="lang-markup" :title="entry.title">
  <template v-slot:content>
      <div v-html="entry.content"></div>
  </template>
    <template v-slot:examples>
      <div v-html="entry.examples"></div>
    </template>
    <template v-slot:code>
        {{entry.code}}
    </template>
  </base-section>
</template>

<script>
export default {
  mounted(){
    this.$nextTick(function () {
    Prism.highlightAll();
    this.getData()
  })
  },
    
  updated(){
    this.$nextTick(function () {
    Prism.highlightAll();
    this.getData()
  })
  },
  methods:{
    getData(){
      const url= 'https://example.dev/api/collections/get/'+this.$route.name+'?token=XXXXXXXXX'
    
    fetch(url)
    .then(collection => collection.json())
    .then(collection => {

      const entries = [];

            for (const id in collection.entries) {
              entries.push({
                title: collection.entries[id].Title,
                content: collection.entries[id].Content,
                examples: collection.entries[id].Examples,
                code: collection.entries[id].Code,

              });
            }

            this.entries = entries;

    });
    }
  },
  data() {
    return {
      entries:[]
    };
  },
};
</script>

THE ISSUE: This setup functions properly. However, there are a couple of concerns bothering me. 1st - The content behaves oddly when switching between routes; the content flickers between both route's content before displaying the correct one 2nn - Observing the DEV TOOLS reveals constant updates on the content (the section tag on the code tab flashes purple repeatedly, indicating updates).

Any advice on what I might be missing?

PS: I am new to VUE JS.

Thank you very much!!!

Regards, T.

Answer №1

Success! I was able to resolve the issue. After thorough investigation, I discovered that all I needed to do was provide a distinctive :key attribute to the <router-view> component in my App.vue file.

So, I implemented the following:

<router-view :key="$route.fullPath"></router-view>

This solution works because Vue's reactivity system recognizes the necessity of reloading the entire component due to the unique key provided, which wasn't present before.

I hope this information proves useful to others!

Best regards, T.

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

Top method for capturing a Vue JS and Quasar app in writing

I attempted to utilize the JSDoc for VueJS plugin according to the documentation but unfortunately, it didn't work out as expected https://github.com/Kocal/jsdoc-vuejs Can anyone recommend a reliable tool for documenting applications developed with ...

Parsing JSON data using PHP and AJAX decoding

I have been searching for a way to pass parameters between the server and client, but I am struggling to find a solution that works. Despite reading extensively online, I have not been able to come up with a functioning solution. Client Side function sen ...

Adding data to a JSON object using AngularJS

When attempting to insert an object into a JSON object, I am encountering an issue where it duplicates the JSON object. Here is a breakdown of the scenario: <input type="text" style="width: 40% !important;" placeholder="Nom" class="input-sm" ng-model= ...

Creating a model with a many-to-many association using Sequelize

Technologies Stack: NodeJs, PostgreSQL, Sequelize, Express. I am working with two linked models (User and Role) through the intermediary table User_Roles. While creating a new user using Sequelize.create(), I need to populate the User_Roles table to specif ...

A step-by-step guide on creating a chainable command in Cypress

Imagine having a variable called username. Now, consider a chainable function that needs to verify whether the username is empty or not. Original Method: if(username !== "") { cy.get('#username').type(username) } Expected Outcome: ...

Confirm before closing the window

How can I get this code to function properly and show a confirmation alert after the user clicks on a button? This is essentially an "exit website button". The confirmation pop-up will have: If "OK" is clicked > the current window will close; If ...

Retrieve the most recently updated or added item in a dropdown list using jQuery or AngularJS

Having a multiple select element with the chosen jquery plugin, I am trying to identify the latest selection made using the change event. Struggling to locate a simple method to access the most recent selection, I am currently inspecting the last item in ...

Error Found in Angular2 Console Inspection

So, when I check the webpage inspection console, I see this error: Uncaught SyntaxError: Unexpected token { at Object.<anonymous> (main.bundle.js:3885) at __webpack_require__ (polyfills.bundle.js:51) at eval (eval at <anonymous> (m ...

Verify Departure on External Links within Wordpress

Let me set the stage for you: We're dealing with a bank website here. So, whenever a user wants to click on an external link (could be to a Facebook page or a partner website), we need to have a notification box pop up saying "You are about to lea ...

Error occurred when sending form data while uploading a file

Upon trying to upload a file using the formData.append(key, value);, an error message is displayed in the value section: The argument of type 'unknown' cannot be assigned to a parameter of type 'string | Blob'. Type '{}' is ...

Display a message stating "No data available" using HighCharts Angular when the data series is empty

My Angular app utilizes Highchart for data visualization. One of the requirements is to display a message within the Highchart if the API returns an empty data set. I attempted a solution, but unfortunately, the message does not appear in the Highchart a ...

Sending Emails with AngularJS

Exploring AngularJs has been a delightful experience for me, and I recently stumbled upon a fantastic plugin for Angular called angular-http-auth. This plugin allows you to seamlessly integrate an identification system. Does anyone know of a similar resou ...

Retrieve child and descendant nodes with Fancytree JQuery

I'm currently utilizing Fancytree and have created the following tree structure: root |_ child1 |_ subchild1 |_ subchild2 |_ subchild3 |_ subchild4 When the selected node is child1, I am able to retrieve the fir ...

What is causing the Firebase emulator to crash when I run my Express code?

This project is utilizing express.js along with firebase. Whenever attempting to access a different file containing routes, it results in failure. Instead of successful emulation, an error is thrown when running this code: const functions = require(" ...

Upgrading from Vuetify 2 to 3 involves replacing the deprecated styles like .v-application, rounded, and flat with

I need help with upgrading from Vuetify/Vue 2 to Vue 3. I don't have much experience in front-end development, but I am responsible for updating some old code to keep things running smoothly. The migration guide is not very clear and assumes a certain ...

What causes the menu icon to shift to the left upon clicking it?

I'm currently working on a website project that involves implementing a fixed navbar with jQuery sliding animation for the menu. However, I've encountered an issue where the "menu_icon" is getting pushed to the left every time the menu slides dow ...

Is there a way for me to initiate another joyride adventure?

Encountering a challenge with my joyride tour - after completing one tour, I aim to commence a second. Despite attempting to trigger the second tour in the postRideCallback function, I find myself stuck in a loop with the first tour. Seeking guidance on re ...

What is the best way to send a JQuery variable using JSON.stringify and retrieve it on the server-side?

I need to pass the value in JSON.stringify and receive it on the Server side. Please note: When I attempt to pass the value directly without utilizing a JQuery variable, everything works smoothly. Without using a JQuery variable (it's functional) d ...

Restricting the input range with JQuery

Need assistance with limiting user input in a text box for amounts exceeding a specified limit. Attempted using Ajax without success, considering jQuery as an alternative solution. Any expertise on this matter? function maxIssue(max, input, iid) { v ...

An Ajax GET request will not be able to locate the JSON file

I am having issues retrieving Key and Values from a JSON file using the function provided. Despite placing the 'datafile.json' in the same directory, the code fails to execute the alert(weblink) function, while the alert('test 1') works ...