Add new navigation links on-the-fly using Vue CoreUI's dynamic navigation feature

I am looking to enhance my CoreUI sidebar in Vue by adding some menu items that load via Ajax. While I have found a workaround solution, I believe it may not be the best approach and could potentially cause timing issues. I am reaching out for suggestions on a proper or more efficient solution.

Interestingly, I came across this unanswered question related to this topic just a few days ago.

// main.js
new Vue({
    el: '#app',
    router,
    icons,
    template: '<App/>',
    components: {
        App
    },
    data: {
        clientConfiguration: null
    },
    created: async function () {
        let svcResult = await this.$http.get('Picking/ViewerSettings');
        this.clientConfiguration = svcResult.data;
        this.$children[0].$children[0].$children[0].$data.nav[0]._children[0].items =
            svcResult.data.map(vc => ({
                name: vc.name,
                to: 'test/' + vc.name,
                icon: 'cil-spreadsheet'
            }));
    }
})

// _nav.js
export default [
    {
        _name: 'CSidebarNav',
        _children: [
            {
                _name: 'CSidebarNavDropdown',
                name: 'Lists',
                to: '/test',
                icon: 'cil-list-numbered',
                items: []
            },
            // ...
        ]
    }
]

Answer №1

The file _nav.js serves as an illustration of a data structure that can be rendered using the CRenderFunction component. For more information, you can refer to the documentation.

CRenderFunction allows for rendering components from Array/Object.

In your situation, there are two options available:

  • Create a CRenderFunction object on the backend,
  • Generate a CRenderFunction object on the frontend using computed properties based on the data received from the backend.

Below is an example demonstrating the second approach:

In the template:

<CRenderFunction flat :content-to-render="navItems"/>

In the script:

// Example array received from backend
const menuItems = [
  { 
    name: 'first item',
    to: '/first',
    icon: 'cil-user'
  },
  { 
    name: 'second item',
    to: '/second'
  },
  { 
    name: 'third item',
    to: '/third'
  }
]

export default {
  computed: {
    navItems () {
      return [
        {
          _name: 'CSidebarNav',
          _children: this.sidebarNavChildren
        }
      ]
    },
    sidebarNavChildren () {
      return menuItems.map(menuItem => {
        return {
          _name: 'CSidebarNavItem',
          name: menuItem.name,
          to: menuItem.to,
          icon: menuItem.icon || 'cil-spreadsheet'
        }
      })
    }
  }
}

Result of navItems computed property:

[{"_name":"CSidebarNav","_children": [
  {"_name":"CSidebarNavItem","name":"first item","to":"/first","icon":"cil-user"}, 
  {"_name":"CSidebarNavItem","name":"second item","to":"/second","icon":"cil-spreadsheet"}, 
  {"_name":"CSidebarNavItem","name":"third item","to":"/third","icon":"cil-spreadsheet"}
 ]
}]

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

Prevent Buttons from Being Clicked While Another is Active in Angular

I am facing a challenge with my Angular functions that enable search features. My goal is to allow only one feature to be selected at a time. /* Trauma Search functionality */ $scope.traumaSearch = false; $scope.traumaText = "Trauma Center"; $scope.togg ...

Tips for updating the left positioning of a Div element on the fly

Although my title may not fully explain my goal, I am dealing with dynamically created div elements. When a user triggers an ajax request to delete one of the divs, I want to remove it from the DOM upon success. The issue arises in adjusting the layout aft ...

Methods for extracting the date value from a Material UI datepicker?

As a newcomer to React, I am currently working on creating a form that includes a Date picker for scheduling appointments. Since booking appointments in the past is not allowed, I need to disable the days before today in the calendar for the date picker. ...

Discover the effective method in Angular to display a solitary password validation message while dealing with numerous ones

Here is the pattern we use to validate input fields: The length of the input field should be between 6 and 15 characters. It should contain at least one lowercase letter (a-z). It should contain at least one uppercase letter (A-Z). It should contain at le ...

Issue: main@HEAD Failed during 'site building' stage: Build script ended with non-zero exit code: 2

11:29:48 AM: build-image version: 3d3c7e8b4321e2c1a54a2c4584fb46ba742b1630 (focal) 11:29:48 AM: buildbot version: 72ed9578274f76ae72cdce4c5312615aeecc32fb 11:29:49 AM: Building without cache 11:29:49 AM: Starting to prepare the repo for build 11:29:49 AM: ...

Ramda Transitioning to a Liberated Style of Programming

Unable to find a suitable resource for this particular issue. I apologize if this question has already been asked, but my attempts to locate the answer have proven fruitless (perhaps due to a lack of effective search methods). I've developed a functi ...

Ways to enhance the input field's value without completely replacing it with a new value using jQuery

My goal is to retrieve the current input id, store it in a variable, and then select that input to add the previously entered value by the user. $("#" + current_cursor_input).prev().val("value added"); It seems that the prev() function does not actually ...

Ways to stop Angular from automatically scrolling to the center of the page

I am facing an issue with my angular 11 application. Whenever I navigate to a specific page, there is an automatic scroll down which I don't want. Please refer to the attachment (gif) and homepage.html below to understand the scenario. https://i.ssta ...

Elastic_Frame | "Error: Unable to process action as property 'toLowerCase' is not defined"

Attempting to create a personal and project portfolio using Vu Khanh Truong's "elastic_grid" jQuery plugin for the actual portfolio. You can access it here. However, encountering some issues on my page: 1) The header for the portfolio section disappe ...

An effective method for injecting a mixin into a component on the fly

A situation has arisen where one of my components needs a mixin based on the props it is given. const timerMixin = { created() { console.log("Timer mixin injected") } } export default { name: 'Component A', props: [&apos ...

Sort the data - a selection menu is included in each row of the table

My issue involves a datatable where each row must have a select item with multiple options to choose from. The goal is to filter the rows based on the selected option when using the default search bar located above the table. However, I've encountered ...

Tips for integrating Vue.js and Semantic UI to create stunning web applications

My interest lies in utilizing Vue.js with Semantic UI, although I am fairly new to this and may not execute it correctly. While searching for guidance on how to integrate the two technologies, such as this resource, the abundance of information can be over ...

The Redis port and host remain unset despite having defined environment variables

While utilizing the redis npm package, I encountered an issue where the host and port values were showing as undefined when trying to connect. Even after checking my process.env object, I could see that the values were properly set. Strangely, it only beca ...

Asynchronous retrieval of reference value from Firebase Firestore in ReactJS

Encountering a peculiar bug in TypeScript-JavaScript where I have a Model class in TypeScript and a ReactJS Component in JS. The issue arises when dealing with a list of Promo Objects, each containing a "_listCompte" property which holds a list of Compte O ...

What is the best method for establishing communication between a Firebase service worker and a Vue/Vuex web application?

Our Vue application is currently using a firebase service worker alongside it. The service worker setup is as follows: // main.js import firebase from 'firebase/app' import 'firebase/messaging' ... const firebase_config = { apiKey ...

Export all entries without taking into account pagination limits

My current setup involves using Datatables with pagination. I recently integrated the Datatable.buttons library to enable an Export to Excel feature. However, I encountered a limitation where only the first 10 rows on the current page are exported due to p ...

Finding MongoDB data using an Express route and displaying it in a Jade template

Is there a way to retrieve data from MongoDB using an express route and display it in a jade template? Below is the code snippet of my express route (express version 2.5.8): app.get('/showData',function(req,res){ db.collection('comme ...

Filtering with checkboxes (looking for help with logic functionality)

Yesterday, I sought assistance with a similar question and was able to make progress based on the response provided. However, I have encountered another issue that has left me stuck. Current behavior: Clicking on a checkbox changes the background color of ...

Utilizing for loop and specific string selectors in an undefined AJAX post request

Greetings fellow developers! I have been exploring jquery/ajax and here is what I've put together: $(function() { $("#moreAdd").click(function() { var dataString = []; var selector = '#repeat0'; var row; for(var i=0;$ ...

Creating a custom loading spinner featuring your logo

Hello, I am looking to create a custom loading spinner using CSS, JS or any other method with my logo. I have the logo in PNG, GIF, and SVG formats and would like to use it for long site loads, image loads, or any other loading processes within my Vue3 pro ...