简体   繁体   中英

Emitting event from child to parent component not working in Vue.js (using class-based decorator)

I am quite new to Vue.js, and for some reason the child to parent emit is not working.

Basically, I have Search component within a Box component. On my Search component, I tried doing:

@Watch("searchValue", { immediate: true })
onSearch(value: string, oldValue: string) {
    console.log(this.searchValue); // this is logged OK
    this.$emit("search-val-change", this.searchValue);
}

Then on the box component template:

<box @search-val-change="doSearch">
    <search></search>
    <ul>
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
    </ul>
</box>

On the box.ts file:

import { Component, Prop, Vue, Watch } from "vue-property-decorator";

@Component
export default class Box extends Vue {
    doSearch() {
        console.log("TEST EMIT"); // nothing is console logged, means it doesn't come to this part at all
    }    
}

I am getting this error:

[Vue warn]: Property or method "doSearch" 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.

...although it is defined as a method. I am using the Vue Class Decorator which states that I can define methods directly.

Anything wrong with the syntax / flow?

The emitted string @search-val-change is on the box component instead of the search child component

It should be something like this

box.vue

 <SearchComponent @search-val-change="doSearch"> ... </SearchComponent>

Also, don't forget to register your search component in the box.vue file. It should be something like this

 @Component({ components: { SearchComponent }, }) export default class Box extends Vue { doSearch() { console.log("TEST EMIT"); } }

Custom methods should be in methods , like so:

@Component
export default class Box extends Vue {
  methods: {
    doSearch() {
      console.log("TEST EMIT"); // nothing is console logged, means it doesn't come to this part at all
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM