Guide to displaying a template using Vue.js

Incorporating jQuery and vuejs version 2.3.4:

https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js

The code snippet below demonstrates my current setup:

      // Instantiating Vue.
      vueVar = new Vue({
        el: '#content',
        methods: {
          // Function to inject a menu link into the DOM.
          inject_menu_link: function (menu_title, menu_url, menu_type) {
            if($(menu_type + ' li').length){
              // Inserting menu link if it already exists
              template = '<menuLinkTpl v-bind:url="'+menu_url+'" v-bind:name="'+menu_title+'"></menuLinkTpl>';
              $(menu_type + ' > li').last().after(template);
            }
          },
        },
        components: {
          // Menu template for adding URL and title of the menu
          'menuLinkTpl': {
            props: [{
              // URL of the menu link
              url: '',
              // Name of the menu link
              name: '',
            }],
            template: '<li><a v-bind:href="\'/\'+ url " v-bind:title="name">{{name}}</a></li>',
          },
        },
      });
<body>
  <div id="content">
    <ul id="block-menu">
      <li><a>menu 1</a></li>
      <li><a>menu 2</a></li>
    </ul>
  </div>
</body>

My goal is to dynamically add a new menu item whenever vueVar.inject_menu_link('menu link title', 'url-test', '#block-menu') is called.

The issue I'm facing is that:

<menuLinkTpl v-bind:menuurl="/url-test" v-bind:menuname="menu link title"></menuLinkTpl>

This HTML tag is being appended to the DOM unrendered.

How can this be resolved?

Answer №1

If you want to dynamically add content, consider using a v-for loop in Vue.js

export default {
    data () {
         return  {
             menuItems: [{ .. initial value ...} ]
         }
    },
    methods: {
        injectMenu () {
            menuItems.push({}).
        }
    }
}

In your template, you can do something like this:

<body>
  <div id="content">
    <ul id="block-menu">
      <li is="menuLinkTpl" v-for="menu in menuItems" :url="menu. ..." :name="menu. ..."></li>
    </ul>
  </div>
</body>

When adding dynamic content with Vue, it's important to remember that text injection may not be the best approach because Vue needs to create a virtual DOM for optimal performance. To learn more about rendering functions in Vue, check out https://v2.vuejs.org/v2/guide/render-function.html You can also use the createElement method to achieve this.

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

Why does the for loop assign the last iteration of jQuery onclick to all elements?

I've encountered an issue with my code that I'd like to discuss var btns = $('.gotobtn'); $('#'+btns.get(0).id).click(function() { document.querySelector('#navigator').pushPage('directions.html', myInf ...

Repair the voting system

In my Ruby on Rails app, I have successfully set up an up/down voting system that utilizes ajax. When a user clicks the buttons, it triggers the create method to insert a vote into the database and calculate the total sum of votes. Currently, users can fr ...

"Create a div element with resizable capabilities, similar to a

Is it possible to resize elements like divs in browsers without using jQuery or other libraries like draggable or resizable? I know text-areas can be resized by default, but I'm curious if this functionality can be extended to other elements through p ...

The desired hover effect on the navigation bar is not functioning properly

I have successfully created a hover effect for my navigation bar and the list inside it. However, I am facing an issue where the box shadow effect is only appearing in a small area when hovered (see image below). My goal is to extend the shadow effect to ...

Utilizing jQuery and AJAX to submit a form

I'm currently facing an issue while attempting to transfer variables from an HTML form to a PHP script using jQuery and AJAX. Despite having successfully done this in the past, I am encountering difficulties this time around as PHP is failing to displ ...

Tips on getting Qtip2 Growl to start at the bottom position

After utilizing Qtip2 in two of my previous projects, I am eager to try out a new feature called Growl. You can find more information about Growl here. My goal is to have the growl start from the bottom instead of above. I have attempted to reverse the c ...

Ajax-enabled pre-resize feature for efficient multiple file uploads

I'm currently facing an issue with a function that involves pre-resizing and ajax file uploading. I have a FOR loop which calls this function, depending on the length of the file input size. The strange thing is, sometimes when I call it multiple time ...

The issue with implementing simple getElementsByClassName JavaScript in the footer of a WordPress site persists

I am facing an issue with a 1-liner JavaScript code in the footer where getElementsByClassName function doesn't seem to work for tweaking style attributes. The text "Hello World" is displaying fine, so I suspect it might be a syntax error? Here' ...

Tips on preventing the opening of a new browser tab by using Ctrl + click

Hey there, I've got a list of products that can be selected using the Ctrl key. $(parentSelector).on("click", function (evnt) { evnt.stopImmediatePropagation(); var item = $(evnt.delegateTarget) ...

Creating a Vue.js webpack build optimized for production platform

This is my first experience using a frontend Build Tool. Up until now, I've only worked with frameworks that were as simple to install as adding a <script> tag to my HTML page. Now you have an idea of my skill level. I am working on a Vue.js/Vu ...

The absence of a closing parentheses in the argument is causing an issue when rendering

Apologies for the basic mistake, but I could really use some assistance with this syntax error. I've spent over an hour searching for it and still haven't been able to locate the issue. It seems to be around the success function(data) section. Th ...

Creating text input without borders using HTML and CSS

I have managed to create text inputs without borders using HTML and CSS, but I am facing an issue. Whenever I click on the input field, a yellow border appears instead of the one I removed. It seems like this is coming from the default stylesheets, and I&a ...

What might be causing Flex not to function properly on my personalized landing page?

I attempted to create a basic landing page featuring an image background with a logo, button, and a row of 4 images displayed side by side using Flex. However, for some reason, the Flex is not functioning properly for the row of images. Here is the code s ...

Struggling to make align-content function properly in a CSS flexbox layout grid

Utilizing CSS flexbox for designing a grid of items that wrap on resizing the page. Wanting to achieve a horizontally centered grid, successfully done with justify-content: center;. However, facing an issue where the last box in some cases is centered inst ...

I am struggling to make php redirect work using onclick() function

My PHP button is not redirecting properly. Assuming the page destination is correct, is there anything else that could be causing this issue? echo "<button id=\"create\" onclick=\"location.href('/team/teams.php?op=create');&bso ...

Is there a way to display (PHP for loop variables) within an HTML table using echo?

for ($q = 1 ; $q < 7 ; $q++ ) { echo $q ; echo $row; } While the above code functions properly, I am interested in echoing two rows as shown in the image below: https://i.stack.imgur.com/7KmUY.jpg I prefer not to use another for loop. Is there a way t ...

Switching the sorting criteria from 'AND' to 'OR' in the JPList library

I am currently exploring the use of JPList to sort on multiple items. As it stands, JPList searches like 'AND' when sorting (e.g. sorting based on an item with tags html, php and jQuery all together), but I am interested in filtering through all ...

I am having trouble with my append function even though I checked the console log and did not see any errors (beginner's inquiry)

As I practice working with functions and dynamically creating input fields, I have encountered an issue where I am unable to append my input field to the form. Despite using console.log() and not seeing any errors, I can't figure out what mistake I ma ...

Troubleshooting Vue 3 Composition API: Issue with Data Access in V-For Loop

Currently facing an issue with a template I have The problem lies with location.drawnfeatures not updating within the template for unknown reasons. I've verified that the data is correct using console.log, and when I tested the code without 'v-f ...

Warning in Vue 3 with ESLint: [intlify] HTML Detection Detected

Encountering a warning in the console stating "[intlify] Detected HTML in .....", yet unable to find a way to disable this specific warning for the mentioned line. Attempts were made to modify the eslintrc.js file to deactivate all v-html warnings, but unf ...