Search code examples
javascriptvue.jscomponents

Pass a method from parent to listener in childcomponent in vue


I have a button in my parent component App.vue and want to listen to buttonclick on my childcomponent and passing an incremental number every time the button is clicked. At the moment I am passing the value as a prop and are watching for a change in my childcomponent with a watch: {

This works fine. However, since I am pretty new to vue I wonder is there a better way or is this the recommended way of doing this?

App.vue

<template>
  <div id="app">
    <button @click="myMethod">To child</button>
    <Mycomponent :myProp="count" />
  </div>
</template>

<script>
import Mycomponent from "./components/Mycomponent";

export default {
  name: "App",
  components: {
    Mycomponent
  },

  data() {
    return {
      count: 0
    };
  },
  methods: {
    myMethod() {
      this.count++;
    }
  }
};
</script>

Mycomponent.vue

<template>
  <div>
    {{myNumber}}
  </div>
</template>
<script>

export default {
  name: "Mycomponent",
  props: {
    myProp: {
      type: Number
    }
  },

  data() {
    return {
      myNumber: 0
    };
  },

  watch: {
    myProp: {
      deep: true,
      immediate: true,
      handler(newValue) {
        try {
          console.log("Print my value in the consule: ", newValue);
          this.myNumber = newValue
        } catch (err) {
          console.log("no data yet ...");
        }
      }
    }
  }
};
</script>

UPDATED EXAMPLE FOR REACHING PROP IN CHILD COMPONENT

<template>
  <div>
// what if I dont want to display myProp in the template? Just store the data
    {{myProp}} 
    <button @click="myMethod">Method</button>
  </div>
</template>
<script>
export default {
  name: "Mycomponent",
  props: {
    myProp: {
      type: Number
    }
  },
  methods: {
    myMethod() {
      console.log("print myProp ", this.myProp);
    }
  }
};
</script>

But what about if I don't want to display the value. Just use the prop as data?


Solution

  • You actually don't need the watcher. Props are reactive, and if you just reference {{ myProp }} in the child component's template, it will re-render whenever the button is clicked.