Home » vue » How to pass vuejs html template as slot and access from data or method

How to pass vuejs html template as slot and access from data or method

Posted by: admin November 26, 2021 Leave a comment

Questions:

I have a component like this:

<my-dropzone value:"...."> 
    <h1>upload</h1>
    <p>your files</p>
</my-dropzone>

and my vuejs component is:

<template>
    <div>
        <div class="dropzone"></div>
        <slot></slot>
    </div>
</template>

<script>
  ....

    export default {
        props:{
           ....
        },
        components: {
            vueDropzone: vue2Dropzone
        },
        data() {
            return {
                arrayFiles: [],
                dropzoneOptions: {

                   ....
                    dictDefaultMessage: // <------ I want to assign slot data here
                    ,
                  ....
        },
        mounted() {
           .....

        },
        methods: {
            .....
        },
        computed: {
           .....
        }
    }
</script>

Now I want to get slot html data and assign to some local variable of component and also use in method. Is it possible? Is there any better solution to pass html to data variable

Answers:

You can use Vue.js vm.$slots to access the slot children as HTML nodes. It is the only recommended way. Official Vue.js docs really explain it well.

You can use render() function for your components instead of template. Slots are designed to be used effectively with a render function. Without render function, using vm.$slots is not really that useful.

Long explanation:

Vue slots are not designed to work the way you need. Imagine slots as a rendering area. Also, a slot doesn’t really contain HTML as a string. It is already passed from virtual-dom and rendered as HTMLElements on screen. By the time code is processed, html as a string has transformed into a render function.

Alternately, If you need to really access the underlying HTML nodes, then consider using plain DOM API like querySelector(), etc. As far as the $refs is concerned, Content within the slot is owned by the parent component and thus you cannot use it.