Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference text that's in '<slot></slot>' in Vue.js

How to reference text that's in in Vue.js?

Vue.component('component', {
  template: `<button><slot></slot></button>`,
  created: function() {
    // i would like to access the text in slot here
  }
});
like image 425
Tadas Majeris Avatar asked Mar 22 '17 11:03

Tadas Majeris


People also ask

How do you access the Vue slots?

To get access to the data passed to the slot, we specify the name of the scope variable with the value of the v-slot directive. There are a few notes to take here: We specified the name of default , though we don't need to for the default slot. Instead we could just use v-slot="slotProps" .

How do you use the Vue named slots?

How to Use Named Slots. There are two steps to using named slots in Vue: Naming our slots from our child component using the name attribute. Providing content to these named slots from our parent component using the v-slot directive.

What is slot props in Vue?

Slot props allow us to turn slots into reusable templates that can render different content based on input props. This is most useful when you are designing a reusable component that encapsulates data logic while allowing the consuming parent component to customize part of its layout.

How do refs work in Vue?

Ref s are Vue. js instance properties that are used to register or indicate a reference to HTML elements or child elements in the template of your application. If a ref attribute is added to an HTML element in your Vue template, you'll then be able to reference that element or even a child element in your Vue instance.


1 Answers

For Vue 3.

The answer from @bert works well on Vue 2, but Vue 3 slots have a more complex structure.

Here is one way to get the slots text contents (from default slot) on Vue 3.

const getSlotChildrenText = children => children.map(node => {
  if (!node.children || typeof node.children === 'string') return node.children || ''
  else if (Array.isArray(node.children)) return getSlotChildrenText(node.children)
  else if (node.children.default) return getSlotChildrenText(node.children.default())
}).join('')


const slotTexts = this.$slots.default && getSlotChildrenText(this.$slots.default()) || ''
console.log(slotTexts)
like image 138
antoni Avatar answered Nov 26 '22 07:11

antoni