6

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
nowox
  • 25,978
  • 39
  • 143
  • 293

1 Answers1

4

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;

Firmino Changani
  • 861
  • 7
  • 11
  • 2
    Do there is no `Vue` wrapper to get this information without hacking the `$refs`? – nowox Aug 15 '20 at 14:37
  • 2
    In which way, using $refs is a hack? Either way, you can use other alternatives to access the element, use one that suits your application best. – Firmino Changani Aug 15 '20 at 14:39
  • 4
    @nowox, `$refs` is exactly that: Vue's wrapper to interact with template entities, whether they're DOM elements or child components (vue instances). It's the exact opposite of a hack. And its only purpose is to allow you (the developer) to interact with the template without hacking. If this need did not exist, `$refs` wouldn't have been added to Vue. – tao Aug 15 '20 at 16:39