Tips for modifying VueJS's <slot> content prior to component instantiation

I am working with a VueJS component called comp.vue:

<template>
  <div>
    <slot></slot>
  </div>
</template>

<script>
  export default {
    data () {
      return {

      }
    },
  }
</script>

When I use this Vue component, the slot content is displayed as shown below:

...
<comp>as a title</comp>
<comp>as a paragraph</comp>
...

My goal is to modify the content of comp.vue's slot before it gets rendered. Specifically, I want to wrap the slot content in different HTML elements based on its contents.

If the slot contains the word "title," then it should be enclosed in an <h1> tag:

<h1>as a title</h1>

If the slot contains "paragraph," then it should be wrapped in a <p> tag:

<p>as a paragraph</p>

Is there a way to dynamically change the slot content of the component before it renders?

Answer №1

It is easier to achieve this by using a string prop instead of a slot. However, if the content is long, using the component in a template can get messy.

If you manually write the render function, you have more control over how the component will be rendered:

export default {
  render(h) {
    const slot = this.$slots.default[0]

    return /title/i.test(slot.text)
      ? h('h1', [slot])
      : /paragraph/i.test(slot.text)
        ? h('p', [slot])
        : slot
  }
}

The render function above only works if the default slot has just one text child (I'm not sure about your requirements beyond what was shown in the question).

Answer №2

To implement dynamic slot structure changes in Vue.js, you can utilize the $slots property like this:

export default {
    methods: {
        changeSlotStructure() {
            let slot = this.$slots.default;
            slot.map((x, i) => {
                if(x.text.includes('title')) {
                    this.$slots.default[i].tag = "h1"
                } else if(x.text.includes('paragraph')) {
                    this.$slots.default[i].tag = "p"
                }
            })
        }
    },
    created() {
        this.changeSlotStructure()
    }
}

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

Tips on successfully passing multiple keys and their associated HTML tag attributes in a React application

One of my links, specified with an a-tag, appears in this manner: <a href={ item.htmlReportUrl } target="_blank" rel="noopener noreferrer"> {item.htmlReportText}</a> The values for the href and the linktext are sourced from the following: ro ...

Exploring the internet with Internet Explorer is like navigating a jungle of if statements

I am facing an issue with my code that works well in Chrome, but encounters errors in IE. The if condition functions correctly in Chrome, however, in IE it seems like the first condition always gets executed despite the value of resData. Upon analysis thro ...

Integrating node.js into my HTML page

Forgive me for sounding like a newbie, but is there a simple way to integrate node.js into my HTML or perhaps include a Google API library? For example: <script>google.load(xxxx)</script> **or** <script src="xxxx"></script> ...

What is the best way to find out if an array index is within a certain distance of another index?

I'm currently developing a circular carousel feature. With an array of n items, where n is greater than 6 in my current scenario, I need to identify all items within the array that are either less than or equal to 3 positions away from a specific inde ...

Ways to bring in a Typescript Vue project to a Javascript Vue

I am trying to incorporate this Calendar component into my Javascript Vue 3 project. To achieve this, I have created a new component in my project named ProCalendar.vue and copied the code from the example found in App.vue. Additionally, I have added the n ...

Struggling to make AngularJS routes function properly

After starting from scratch, I rebuilt it with freshly downloaded angularJS (version 1.5.8). I simply placed both angular.js and angular-route.js in the library folder following this setup: https://gyazo.com/311679bf07249109671d621bc89d2d52 Here is how in ...

Looking to arrange an object by the value of a nested object in Typescript/Angular?

I'm currently developing an Angular 9 application focused on covid-19 cases, and I need to arrange my objects by the value of nested objects. Here is the dataset that I want to organize alphabetically based on the 'state' field values: stat ...

Unlocking supplemental JSON data in a Dynatable AJAX query

I have implemented the dynatable.com plugin to generate a table of schools from our database. The table is dynamic and can be filtered, so it does not always display the total number of schools. While we do not include a 'number of pupils' column ...

Attempted to fetch information using Ajax in Grails

I am attempting to utilize jQuery and ajax with the Grails framework to load the content registration page. However, upon loading the page, I am encountering an issue where the menu and registration fields are duplicated within the page. <script src ...

Exploring Cypress: Leveraging the Power of Variable Assignment

Recently, I encountered an issue while working with a variable in a Cypress each loop. Despite incrementing the variable within the loop, it resets to zero once outside of it. Can someone shed light on why this happens and suggest a solution? Thank you. p ...

Is there a way to utilize JSON parse for converting deeply nested keys from underscore to camelCase?

A JSON string containing an object is on my mind: const str = `[{"user_id":"561904e8-6e45-5012-a9d8-e2ff8761acf6","email_addr":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="caa0a3a6a5bc8aaca ...

Issue with JQuery dialog not triggering autocomplete

I have integrated the JQuery 1.7.2 and JQuery-UI 1.8.18 libraries with both http://docs.jquery.com/UI/Dialog and http://docs.jquery.com/UI/Autocomplete. On a standard page load, the autocomplete function works perfectly with a text box in a form. It' ...

When trying to access document.cookie, an empty string is returned despite the presence of cookies listed in developer tools, and the httpOnly flag is set

There are times when I encounter an empty string while trying to access document.cookie on the login page, despite the following conditions being met: The cookies are visible in the Chrome and Firefox developer tools, The httpOnly flag of the cookie I&ap ...

Troubleshooting Guide: Issues with Bootstrap 3 Modal Window Implementation

This question is so simple that it's embarrassing. I attempted to copy the code from http://getbootstrap.com/javascript/#modals directly into a basic page setup, but it's not functioning. It seems like I'm making a very silly mistake. Here i ...

Changing the style of opening curly braces in JavaScript code styling

I have a piece of JavaScript code written for Vue that I would like to discuss. It is common practice in the JavaScript world to place the opening curly brace at the end of a line of code. <script> export default { name: 'newUser', data ...

Transfer a script from a view to application.js in Rails: Guide and Instructions

After conducting some research, I found a code that worked well for me in the view. However, I am looking to transfer it to application.js so that I can utilize it in various forms. Another issue I encountered is having two scripts performing the same fun ...

What steps do I need to take to integrate Twilio's SMS service into an HTML document?

I have been searching for solutions using php and node.js (which is a derivative of js, so it should work), but I came across this library: <script type="text/javascript" src="//media.twiliocdn.com/sdk/js/client/v1.4/twilio.min.js"></script> ...

Checking a sequence using a list of strings

I have an array containing a list of IDs: var listId: string[] = []; var newId: boolean; for (let i in data.chunk) { listId.push(data.chunk[i].aliases[0]); } My objective is to compare a new ID with the entire list. If the new ID is found in the list ...

Typeahead.js is a powerful tool offered by Twitter that allows for easy auto-completion

I am currently working on a program that has the capability to search for specific university courses based on certain parameters. Within my large JSON object, there are 1360 objects, each consisting of around 20-30 parameters. However, I am only intereste ...

What is the best way to establish communication between methods in a React application?

In the SelectedTopicPage component, I currently have two methods: navigateNext and render. My goal is to pass the value of topicPageNo from the navigateNext method to the render method. What is the best way to achieve this in React? When I attempt to decla ...