[Vuejs]-Vue 2 Component not calling main instance function

2👍

You don’t emit functions. You emit events.

You need to listen for the toggleHouse event, and I would additionally recommend never using camel cased event names (for reasons beyond the scope of this answer).

Let’s assume you change to use toggle-house instead.

this.$emit('toggle-house', value)

Where you use the property-house should look like this

<property-house :value="true" @toggle-house="toggleHouse"></property-house>

Note the @toggle-house. This is the shortcut method for listening to an event in Vue; you could also use the full syntax, v-on:toggle-house="toggleHouse".

In either case (using @toggle-house or v-on:toggle-house) a listener is set up that listens for the toggle-house event you are emitting from the child component that calls the toggleHouse method when the event occurs.

Here is a very rudimentary example.

console.clear()

Vue.component("property-house", {
  template: `
    <div>
      <button @click="$emit('toggle-house', 'Clicked the button')">Click Me</button>
    </div>`
})

new Vue({
  el: "#app",
  methods: {
    toggleHouse(message){
      alert(message)
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>

<div id="app">
  <property-house @toggle-house="toggleHouse"></property-house>
 </div>
👤Bert

0👍

I needed to change the strategy since @click="callFunc" was taking the opposite checkbox value, I guess, that event was fired before changing the v-model="data".

Therefore my new components look like this:

<template>
    <fieldset class="form-group col-md">
        <div class="form-check">
            <input
                class="form-check-input"
                type="checkbox"
                id="house"
                name="house"
                v-model="data">
            <label
                for="house"
                class="form-check-label"
            >House</label>
        </div>
    </fieldset>
</template>

<script>
    module.exports = {
        props: {
            value: {
                type: Boolean,
                required: false
            }
        },
        data: function() {
            return {
                data: false
            }
        },
        created: function() {
            if(this.value) {
                this.data = this.value;
            }
        },
        watch: {
            data: function(value) {
                this.$emit('callback', value);
            }
        }
    }
</script>

Leave a comment