[Vuejs]-Use slot-scoped data in the component script in Vue

0👍

If you use slot-scope you are basically passing data to the slot, from the component, which is hosting the slot (not the with the content of the slot).
In your case if you want to use data slot-scope, you have to pass the data from component A. So the data-source myObject must exist in component A.

So the right approach would look something like this:

Component A

<template>
    <div>
        <slot :myObject="myObject" />
        <button @click="changeMyObject">Change MyObject</button>
    </div>
</template>
<script>
    export default {
        name: "slot-scope-component",
        data(){
            return {
                myObject: {
                    value: "ABC"
                }
            }
        },
        methods:{
            changeMyObject() {
                this.myObject = {
                    value: "XYZ"
                };
            }
        }
    }
</script>

Component B

<template>
    <ComponentA>
        <template slot-scope="props">
            {{props.myObject}}
        </template>
    </ComponentA>
</template>

<script>
    import ComponentA from '@/components/ComponentA';

    export default {
        components: {
            ComponentA
        },
    }
</script>

As well there was a little spelling mistake: You wrote slot-scoped instead of slot-scope

You can improve that code further by using destructuring:

slot-scope="{myObject}"

Leave a comment