Get slot data as a variable in Vue? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Get slot data as a variable in Vue? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have a component (prism-editor) that only takes code from v-model="code". This means, the code has to be sent to the component through code:

Code.vue

<template>
  <prism-editor class="my-editor" v-model="code" 
    :highlight="highlighter" :line-numbers="numbers"/>
</template>

<script>  
  import { PrismEditor } from 'vue-prism-editor';

  export default {
    components: {
      PrismEditor,
    },
    data: () => ({
        code: this.$slots,
        numbers: true
    }),
  }
</script>

I would like to bind this from a parent component named Code from a slot:

Page.vue

<template>
    <code language="c">
        int main() {
            printf('Hello World!');
        }
    </code>
<template>

<script>
  import Code from 'code.vue'
  export default {
    components: {
      'code': Code
    }
  }
</script>

In my Code component, I have to find a way to get and pass the slot data directly to the code variable to be sent to the v-model='code'. Unfortunately the following doesn’t work because I don’t know how to get the data from the parent slot:

data: () => ({
    code: this.$slots // Which obviously doesn't work...
})

Said differently, I just want to get all the raw content that was sent inside the code tag:

<code>all this content...</code>`

Is this possible?

.
├── Code.vue
└── Page.vue

Answer

Great question, in order to solve that you would have to go a layer below Vuejs, and use the property textContent from the DOM API [read more here]

With this property you can access the content inside of a DOM element, so in your case it would be something like:

/*
 * Template
 */
<div ref="mySlot">
  <slot></slot>
</div>

/*
 * Javascript
 */
this.$refs.mySlot.textContent;

I’ve setup a nice example for you in Codesandbox:

https://codesandbox.io/s/gallant-resonance-7unn2?file=/src/components/Code.vue

For future challenges:

Always try to see if you can solve it with pure Javascript. Happy coding mate;

We are here to answer your question about Get slot data as a variable in Vue? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji