Ohmry Lee
Ohmry Lee

Reputation: 11

Accessing components data from slot in vue.js (without declare template in outskirts)

Being create Menu components use to frameless windows. but I don't know how to bind events into slot. I want to build structure like this

in WindowBar.vue

<template>
  <div>
    <app-menu-bar>
      <app-menu label="File"></app-menu>
    </app-menu-bar>
  </div>
</temaplte>

in AppMenuBar.vue (name is app-menu-bar)

<template>
  <section>
    <slot
      v-bind:onSelected="onSelected"
      v-on:doClick="doClick"
    >
    </slot>    
  </section>
</template>

<script>
export default {
  name: 'app-menu-bar',
  data () {
    return {
      onSelected: ''
    }
  }
}
</script>

in AppMenu.vue (name is app-menu)

<template>
  <section class="menu">
    <button 
      v-on:click="doClick"
      v-bind:class="isSelected"
    >
    {{ label }}
    </button>
  </section>
</template>

<script>
export default {
  name: 'app-menu',
  props: {
    label: String
  },
  computed: {
    isSelected () {
            // This is binding data from AppMenuBar
      return this.onSelected == this.label ? 'selected' : ''
    }
  },
  methods: {
    doClick () {
      this.$emit('doClick', this.label)
    }
  },
  mounted () {
    console.log(this.onSelected)  // it is undefined
  }
}
</script>

how do i binding data into slot, like this.onSelected?

Upvotes: 1

Views: 59

Answers (1)

f1etcher
f1etcher

Reputation: 9

You can't listen to events on <slot>. The more detailed answer you can read here https://github.com/vuejs/vue/issues/4332.

In your case, I will suggest putting all business logic in the parent component (which is WindowBar.vue). After that, you can have control of your child's component events and props. Or, if there is some specific situation, and you want to pass events through nested components you can use the event bus for it. More about the event bus you can read here: https://www.digitalocean.com/community/tutorials/vuejs-global-event-bus

Upvotes: 1

Related Questions