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 for automatically incorporating animation upon page initialization

I'm looking to add an automatic image effect when the page is loaded. I currently have this code in my js file: $(window).ready(function(){ $(pin).click(function(){ $("#pin01").show().animate({left: '650px'}); }) }); Here is the HTML wit ...

Switch up the like button for users who have previously liked a post

Greetings, I trust everything is going well. I am attempting to implement a feature where users can like a post or article created by others using a button. I have established a const function named "getAPostLikeRecord()," which retrieves a list of users w ...

Having trouble getting a new input box to be added when clicking with AngularJS?

I am facing an issue with adding dynamic form fields to the database using PHP. I have utilized angular for this purpose, but only the last form field is getting inserted into the database. To address this, I attempted using arrays and loops to increment a ...

Generating a fresh document in MongoDB using Mongoose, complete with references and assigned ObjectIDs

I've been attempting to use the mongoose create function in order to generate a new document with references, but I'm encountering an error when trying to provide objectIds for those refs. Despite my efforts to find a solution, I have been unsucc ...

"Utilize a custom filter in AngularJS to narrow down data based on specified numerical

Can anyone assist me in creating a filter for AngularJS data? I have two inputs, minAgeInput and maxAgeInput. I want to retrieve all products/objects (using ng-repeat) where the product's minimum age and maximum age fall within the limits set by the ...

Issue encountered while generating a package using npm init in Node.js

I am currently in the learning process of NodeJs from tutorialspoint(TP). Following instructions provided in this link, I tried to create a package by running the following command: C:\Program Files (x86)\nodejs>npm init This utility will w ...

Verify the text file for any data, and if it contains any, display it on the web browser using JavaScript

I have a program in C that works with a temperature sensor. It creates a file to store the temperature and indicates whether it falls within specific values. I want to display this data on a web browser and update it every 5 minutes. I'm looking for ...

converting a JSON object into an array

I'm facing a challenge and unsure how to proceed. I have received JSON data from an API: https://i.stack.imgur.com/GdDUo.png When I log the data, this is what appears in the console: https://i.stack.imgur.com/GjSPW.png My goal is to extract the id ...

Tips on getting the dropdown value to show up on the header when it changes using Angular 2 and TypeScript

I need assistance with creating a dropdown field in Angular2. When the user selects "car", I want it to display beside the heading. Can anyone provide guidance on how to achieve this? HTML: <h1>Heading <span *ngFor= "let apps of apps">({{apps ...

The FaceDetector within the expo application continues to activate the "onFacesDetected" event in "accurate" mode unnecessarily, even when no face is present

Just starting out with react native and I've been exploring the use of expo FaceDetector for detecting faces. In "fast" mode, the "onFacesDetected" event is triggered correctly. However, when switching to "accurate" mode, the "onFacesDetected" event k ...

Can you explain the distinction between "javascript:;" and "javascript:" when used in the href attribute?

Can you explain the distinction between using "javascript:;" and just "javascript:" within an anchor tag's href attribute? ...

TypeScript async function that returns a Promise using jQuery

Currently, I am facing a challenge in building an MVC controller in TypeScript as I am struggling to make my async method return a deferred promise. Here is the signature of my function: static async GetMatches(input: string, loc?: LatLng):JQueryPromise& ...

Ways to verify if an element includes a specific class in JavaScript

When the mouse hovers over each paragraph within the DIVs with the "change" class, the font color should turn red, and revert back to black when the mouse is not on them. Here's my current code: var paragraphs = document.getElementsByTagName('p& ...

Using Modal Functions in AngularJS Controller

I have been working on a project that utilizes the ui.bootstrap. As per the instructions from the tutorial I followed, my setup looks something like this: 'use strict'; angular.module('academiaUnitateApp') .controller('EntryCtr ...

Ways to extract a single digit from the total sum of a date in the format of 15-06-2015

Is there a way to extract a single digit from the sum of a number in date format, such as 15-06-2015? My goal is to convert the date format 15-06-2015 into a single-digit value by adding up the numbers. For instance: In the case of 15-05-2015, the output ...

Refreshing an iframe located on disparate domains

There is a webpage called "main.jsp" within the domain "domain1". This page contains an iframe that loads content from another domain known as "domain2". Essentially, "main.jsp" serves as a common content platform, with the iframe displaying content from v ...

When working with AngularJS routing, utilize a function for the templateUrl to dynamically load the appropriate template

Can a function be used as the templateUrl in angularjs routing? The $routeProvider official documentation states: templateUrl – {string=|function()=} Check out the $routeProvider official documentation here In javascript, a function is typically def ...

jQuery deduct a value from a given value

i have a full duration that is divided into multiple sections, the user needs to input the duration for each section i would like the system to calculate and display the remaining duration from the full duration, regardless of whether the user fills out ...

Exploring the possibilities of combining Vue 2 with Quasar framework

Embarking on a new project using Vue 2 and Quasar has been exciting for me. I began by executing npm install -g @quasar/cli, followed by quasar create app-name. Upon exploring the created application, I noticed the presence of the setup(){ } function wit ...

Patience is key for a fully completed JSON in JavaScript

I recently came across a similar discussion on Stack Overflow, but it involved using JQuery which I'm not using. My issue is that I need to ensure my JSON data is fully loaded before calling my function. I understand the concept of using a callback, ...