Tips for transferring an item from a v-for loop to a function in Vue.js

I want to implement a cleaner version of the following code snippet:

<div v-for="section in sections">
  <h1 v-if="section.level === 1">
    ...
  </h1>
  <h2 v-else-if="section.level === 2">
    ...
  </h2>
  <h3 v-else-if="section.level === 3">
    ...
  </h3>
  <h4 v-else-if="section.level === 4">
    ...
  </h4>
  <h5 v-else-if="section.level === 5">
    ...
  </h5>
  <h6 v-else-if="section.level === 6">
    ...
  </h6>
</div>

Instead of having logic in the template, I would like to abstract it into functions. Here is an example:

<div v-for="section in sections">
  <h1 v-if="isLevel(section, 1)">
    ...
  </h1>
  <h2 v-else-if="isLevel(section, 2)">
    ...
  </h2>
  <h3 v-else-if="isLevel(section, 3)">
    ...
  </h3>
  <h4 v-else-if="isLevel(section, 4)">
    ...
  </h4>
  <h5 v-else-if="isLevel(section, 5)">
    ...
  </h5>
  <h6 v-else-if="isLevel(section, 6)">
    ...
  </h6>
</div>

I am new to Vue.js and looking for the best way to achieve this. One approach I can think of is creating custom components for each heading level (pseudo code):

<div v-for="section in sections">
  <MyHeader section="{{ section }}" />
</div>

new Vue({
  template: the MyHeader one,
  props: {
    section: true
  },
  methods: {
    isLevel1: function() {
      return this.$data.section.level === 1
    },
    isLevel2: function() {
      return this.$data.section.level === 2
    },
    ...
  }
})

<template name="MyHeader">
  <h1 v-if="isLevel1">
    ...
  </h1>
  <h2 v-else-if="isLevel2">
    ...
  </h2>
  <h3 v-else-if="isLevel3">
    ...
  </h3>
  <h4 v-else-if="isLevel4">
    ...
  </h4>
  <h5 v-else-if="isLevel5">
    ...
  </h5>
  <h6 v-else-if="isLevel6">
    ...
  </h6>
</template>

While this approach works, I find it cumbersome to create custom components for each heading level. I want to explore the idiomatic way of handling this in Vue.js without directly using the render function. Any insights or suggestions would be appreciated!

Answer №1

To accomplish this task, you can utilize the component feature with the is property:

<div v-for="segment in segments">
  <component :is="'h'+segment.level" ></component>
</div>

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

Set the property state to false based on the value of another property in Mongoose Express NodeJS

I am trying to update the status property of a sale based on the outstandingBalance value being equal to 0. Currently, I am able to successfully update the "outstandingBalance", but I want to automatically change the status if it reaches 0. Below is the c ...

Encountering issue with jQuery - Ajax causing error 500 for select posts

Recently, I encountered an issue with the Ajax functionality on a live website. It was previously working perfectly fine, but suddenly started returning a 500 internal server error instead of the expected page. Oddly enough, I discovered that I could stil ...

When the jQuery document is ready, it typically returns null, but the console can still access and display

I have encountered an issue while working on a solution within a CMS (EPiServer). When I utilize console.log to check my object, it displays a null value. $(document).ready(function () { console.log("$('.EPiRequester').html() =" + $('. ...

Angular Pagination: An issue arises when deleting records from the first page, as the following page's records are not automatically refilling the first page

I have implemented angular pagination to display records. Each record has a button labeled 'Assign to me'. Clicking on this button removes the selected record from the list. However, I am facing an issue where I display 10 records per page and if ...

What is the best way to include an <a href=""> tag within $(this).clone() function?

Within my <div id="myPost"><, I've used the Jquery clone function as follows: $(this).clone().appendTo('#myPost');. I'm looking to make this div clickable, directing users to another page. How can I nest an a href tag within t ...

Is there a way to detect browser errors using JavaScript or Angular 2?

On the back-end, I am looking to add these uncaught errors to the log file. These errors are not being captured in angular2. How can I go about reading and handling these errors?https://i.sstatic.net/Kljon.png ...

Facing a problem with querying interfaces and types in TypeScript

My goal is to pass a variable to an RTK Query API service that uses a typescript interface: const device_id: unique symbol = Symbol(props.id); const { data: device, isFetching, isLoading, } = useGetAssetsByIdQuery(device_id, { pollingInterv ...

Is there a method in Vuejs to choose a tab and update components simultaneously?

Currently facing an issue where selecting a tab does not refresh the input field in another component, causing data persistence. The data is stored in vuex, so I'm looking for a solution to refresh the component for usability. Appreciate any assistanc ...

Trigger a click event on a div element that is nested within a form

Having trouble displaying an alert when clicking on a disabled button because the user needs to first click on a terms checkbox. Here's my jQuery code: $('#divButton').on("click", function() { if ($('#buybutton').prop('d ...

Automatically assigning IDs to all elements on an Angular webpage

We are currently developing an enterprise web application and have brought on board an e2e test engineer to automate tests. The test engineer has requested that we assign IDs to all elements in our pages. Is there a tool or method available to automatical ...

Encountering a issue when trying to click the Menu icon in a Vue 3 admin template

i recently set up the CoreUI Vue admin template CoreUI Vue Template. Everything seems to be working smoothly, except for the menu icon https://i.stack.imgur.com/tOShL.png. Whenever I try to hide the side bar (which is a built-in feature), it's not fu ...

Issue with object transformation causing clipping problem in Three.JS

I am currently working on an extension object clipping with 6 planes. The constant of the plane is being controlled by 3 scroll bars, which can be seen below: [ https://i.sstatic.net/eHFho.png The original clippingPlanes are as follows: var localPlane_x ...

Having trouble accessing the property 'prototype' of null in Bing Maps when using Angular4

I'm currently working on creating a Bing component in Angular 4, but I'm facing issues with rendering the map. Below is my index.html file: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title> ...

Updating the Scale of the Cursor Circle on my Portfolio Site

I attempted to find tutorials on creating a unique circle cursor that can hide the regular mouse cursor as well. After implementing it with a difference blend mode, I encountered an issue where I wanted the scale to change when hovering over a link. The ...

Preventing script-src with Content Security Policy in a React application

Everything seemed to be running smoothly with my create-react-app, but out of nowhere, my console started showing this error message: Content Security Policy: The page’s settings blocked the loading of a resource at inline (“script-src”). (this occur ...

How are the actions in react redux able to utilize dispatch and getState methods?

Could you please explain how the actions.js in the reddit example of the react redux docs is able to access the dispatch and getState functions without importing them explicitly? I was under the assumption that every method needed to be imported in each ...

Assign a class to the initial element of the Vuetify v-select module

Hey there! Currently, I'm utilizing the v-select component from Vuetify. I'm looking to customize the appearance of the first item in the v-select component by adding a specific class. For example, I want the text of the first entry "Item A" to b ...

How can I utilize NuxtJS to dynamically transfer color values stored in a JSON file to CSS variables?

I am retrieving colors from the backend using Vuex store, and I want to assign these colors to CSS variables. These variables should be accessible on every page. How can I achieve this? ...

Tiny adjustment to jQuery Collapsible Panel

I have successfully implemented a jQuery Accordion in my demo. When I click on 'About Us', it reveals the 'Team' link below. Exciting! Now, I am wondering if it is possible for this Accordion to function without needing the 'item& ...

Accessing the ID of individually selected rows as well as multiple rows in Vuetify data tables by utilizing the "show select" property

In order to delete specific records from the tables based on user selection, there needs to be functionality implemented where if a user selects any 3 options, a delete button will appear. This delete button should allow for the deletion of those specifi ...