MarcinL
MarcinL

Reputation: 130

Binding method to a slot property

I am using VUE 2.6.11 and class components. I am trying to wrap components that can be displayed as modal inside a component that will manage the modal state.

As per docs I can access my child props/methods in a parent component with Scoped Slots For some reasons my method does not bind to a template:

Modal.vue:

@Component
export default class Modal extends Vue {

  @Prop(String) icon !: string
  @Prop({ default: 'Open popup' }) tooltip !: string

  isVisible = false

  toggleModal() {
    console.log('toggleModal from Modal')
    this.isVisible = !this.isVisible
  }

  toggleModalFactory = 'simple property'
}

Template:

<div >
  <div v-if="isVisible" class="page overlay" >
    <div class="page-content" >
      <div class="dialog-content" >
        <div class="row col" >
          <slot :toggle-modal="toggleModal" />
        </div >
      </div >
    </div >
  </div >
  <button class="btn-primary btn-icon"
          :title="$t(tooltip)"
          @click="toggleModal()" >
    <i :class="icon" />
  </button >
</div >

Then in my Parent I do the following:

<modal icon="plus-icon" v-slot:default="modal" >
  <test-component :toggle-modal="modal.toggleModal" ></test-component >
</modal >

Dev tools claim my method is bound dev-tools

But when I execute the prop function in my nested modal content:

export default class TestComponent extends Vue {

  @Prop() toggleModal !: Function

  @Emit()
  dismiss() {
    this.toggleModal()
    console.log('dismiss from TestComponent')
  }

  @Emit()
  accept() {
    this.toggleModal()
    console.log('accept from TestComponent')
    return 'close-success'
  }
}

I get following errors:

[Vue warn]: Property or method "toggleModal" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.

and:

TypeError: this.toggleModal is not a function

I have found this post (which actually points to docs I mentioned at the begining but I don't see a difference that breaks my code

Upvotes: 0

Views: 1390

Answers (1)

MarcinL
MarcinL

Reputation: 130

A story of a developer loosing his life:

My TestComponent was missing the @Component annotation ...

<script lang="ts" >
import { Emit, Prop, Vue, Component } from 'vue-property-decorator'

@Component
export default class TestComponent extends Vue {

  @Prop(Function) close !: Function

  @Emit()
  dismiss() {
    this.close()
    console.log('dismiss from TestComponent')
  }

  @Emit()
  accept() {
    console.log('close', this.close, this)
    this.close()
    console.log('accept from TestComponent')
    return 'close-success'
  }
}
</script >

Upvotes: 1

Related Questions