Using Vue.js with the slot-in attribute

Looking to create a unique vue.js template that functions as described below:

  • <CustomComponent></CustomComponent>
    should produce
    <div class="a"></div>
  • <CustomComponent>b</CustomComponent>
    should result in
    <div class="a" data-text="b"></div>
    .

Is it possible to achieve this functionality?

UPDATE

Below is the closest solution I've come up with:

  props: {
    text: {
      type: [Boolean, String],
      default: false
    }
  },

and the corresponding template:

<template>
  <div :class="classes()" :data-text="text">
    <slot v-bind:text="text"></slot>
  </div>
</template>

However, there seems to be an issue with the binding, as text always returns false.

Answer №1

To retrieve text content from a component, you can utilize the mounted() method along with the $slot.default property. By creating a data field for text and updating it inside the mounted() method, you can easily access the enclosing text. Here's an example:

Vue.component('mycomponent', {
  data: () => ({
    text: ""
  }),
  template: '<div class="a" :data-text=text></div>',
  mounted(){
    let slot = this.$slots.default[0];
    this.text=slot.text;

  }
});

Please note that this approach is suitable for retrieving text content only, and may not work with HTML tags or other components.

Answer №2

It seems like you're blending slots and properties together in your code. To set the data-text attribute in your component, you'll need to pass the desired value as a prop.

<MyComponent text="'b'"></MyComponent>

In your template, you can then eliminate the slot:

<template>
    <div :class="classes()" :data-text="text"></div>
</template>

Additionally, it appears that you are binding your classes using a method. Consider utilizing computed properties for this purpose instead if you are unfamiliar with them.

Answer №3

Feel free to give this a shot.

<template>
  <div :class="classNames()">
    <slot name="content" v-bind:text="textContent" v-if="hasDefaultSlot">
    </slot>
  </div>
</template>

computed: {
    hasDefaultSlot() {
        console.log(this)
        return this.$scopedSlots.hasOwnProperty("content");
    },
}

Usage:

<MyComponent>
<template v-slot:content="info">
c
</template>
</MyComponent>

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

When functions are sent to children of a react component, they do not inherit the context of the parent

I'm facing an issue while working with React where I am encountering difficulty passing a function from a parent component to multiple children components. The function calls other functions that are also housed within the parent component. Although ...

Avoiding node package trigger errors in another setting

I am facing an issue with my browser extension that utilizes Webpack. The problem lies in a specific package called webextension-polyfill, which throws an error when the script is executed outside of the extension environment. Typically, this wouldn' ...

Instructions on how to navigate back one page to determine which page initiated the action

I am looking for a solution to implement a back button that takes me back one page while caching it. Currently, I am using the following code: <a id="go-back" href="javascript:history.go(-1)" type="button" class="btn btn-danger">Back</a> Howe ...

Slider Jquery - Displaying Half-Step Visual Bar Lengths

JSFIDDLE $(function() { $( "#slider-range-min" ).slider({ range: "min", value: 5, min: 0, step: .5, max: 10, slide: function( event, ui ) { $( "#amount" ).val(ui.value); ...

Does an async function get automatically awaited if called in a constructor?

I am currently working on updating some code due to a library upgrade that requires it to be made async. The code in question has a base class that is inherited by other classes, and I need to call some functions in the constructor that are now asynchronou ...

A comprehensive guide on executing tasks prior to offering downloadable assets in Vue

In my Vue project, I am looking for a way to monitor file downloads. The idea is to generate a URL such as mysite.com/some/path/file-name.txt/tracking-source, trigger an action like sending the path to a tracking API, and then serve the file at mysite.com/ ...

Using Node.js: Interacting with npm inside a module

Is there a more efficient way to implement self-updating functionality for a globally installed module than using the code snippet below? require("child_process").exec("npm update -g module-name"); I came across some documentation regarding installing np ...

Inserting data into a table using variables in Mssql database management system

I'm really struggling to find a way to safely add my Variables into an MSSQL server. I've tried everything. Could someone please help me and provide the solution for adding my Variables into the Database? It is crucial that I prevent any possib ...

What is the best way to create three buttons for selecting various parameters?

I have a code snippet where I want to assign different parameters to each button when clicked. However, despite my logic, the functionality is not working as expected. Can someone help me with the correct syntax? For example, if I click the "Start (Easy) ...

Tips for displaying real-time error notifications from server-side validation using AJAX

Seeking a way to display inline error messages from my Symfony2 Backend without refreshing the page. I considered replacing the current form in the HTML with the validated form containing the error messages returned by the backend through AJAX. However, ...

Prevent refreshing Google Maps when changing routes in AngularJS

Utilizing a Google map as the background for my website adds a unique visual element to the data displayed on different routes. However, I have encountered an issue where the map reloads with every route change, resulting in an unsightly flash of white tha ...

Retrieving information from MySQL using javascript

I am trying to fetch data from a MySQL database using JavaScript. This is the script I have used to load the JavaScript: <script type="text/javascript" src="http://www.domain.de/content/entwicklung/layer.js"></script> Here is the actual scri ...

Animate the parent container of ng-view in Angular by targeting an element within ng-view

Are you able to use CSS animations to animate a div's background color that is located outside of the ng-view, while using a directive on a $state within the ng-view? The ng-view already has CSS animations for routing. When I try to add animation cl ...

What circumstances call for the use of bot protection in user interface interactions?

The question I have is quite general, but I will make it more specific by providing my own use case. Instead of using forms on my websites, I rely on ajax calls to php services. Essentially, I utilize stylized spans with "click" events attached to them, w ...

Is it possible for a button to simultaneously redirect and execute a function using asynchronous JavaScript?

After browsing through several related posts, I realized that most of them were using href to redirect to a completely new webpage. However, in my JavaScript code, I have a button that utilizes the Material-UI <Link>. <Button component={Link} to= ...

Issues with the functionality of the shopping cart are causing a disruption

This is the coding for the online shopping cart: <!DOCTYPE html> <html lang="en-us"> <head> <meta charset="UTF-8" /> <title>Online Shopping Cart</title> <script src="jquery-3.1.1.min.js"></script> ...

Error in THREE.js: The function material.onBeforeRender is not defined

Can someone assist me with an error I'm encountering while trying to run my code in Three.js? The error message reads as follows: three.js:19528 Uncaught TypeError: material.onBeforeRender is not a function at renderObject (three.js:19528) at ...

There seems to be a syntax error lurking within npm.js, and for some reason npm insists on utilizing version 10.19.0 of Node.js despite my attempts to update it. The reason behind this behavior

Apologies if this question seems silly, but just a couple of days ago my code was running perfectly fine. Then today when I tried to load it, I encountered all sorts of errors. I am fairly new to node and npm, so I suspect it could be related to version ma ...

Animate the parent view with Angular UI Router

My current state setup is nested as follows: .state('contacts', { url: '/contacts', views: { '': { templateURL: 'views/contacts.html', contacts: 'ContactsCtrl' ...

Steady Navigation Bar in Javascript without Bouncing

While experimenting with a fixed navigation bar, I've encountered an issue where the content below jumps up on the page when the navigation bar "fixes" itself to the top of the screen. You can check out the JSFiddle I've been working on for refer ...