0
votes

https://jsfiddle.net/56odmcxk/42/

I've used Vue and was able to passed methods as props. In the code example, parent, child and grand child. Child can pass the method to grandChild, which both are declared via Vue.component. But I can't pass the method from parent to child. I am new to Vuejs, please explain if it is scope issue or $root methods are not defined when creating the components causing undefined property in Child component. PS. I recycled some code from similar question to give the demonstration.

Vue.component('grandchild', {
  template: '<div>grandchild - {{ data2.value }}</div>',
  props: ['data2', "secondMethod"],
  mounted(){
    console.log("this is grand child");
    this.secondMethod();
  }
});

Vue.component('child', {
  template: '<div>child - {{ data1.id }}<grandchild :secondMethod="secondMethod" v-bind:data2="data2"></grandchild></div>',
  props: ['data1', 'testChildMethod'],
  mounted() {
    console.log("child element is mounted");
    /* this.testMethod() */;
    this.testChildMethod();
  },
  computed: {
    data2() {
      return {
        value: this.data1.id
      }
    }
  },
  methods: {
    secondMethod(){
        console.log("second method");
    }
  }
});

let v = new Vue({
  el: '#div',
  data: {
    data1: {
      id: 3
    }
  },
  methods: {
    testMethod() {
      console.log("test method is passed");
    }
  }
});


setInterval(function() {
    v.testMethod();
/*   v.data1.id++; */
}, 1000);
1
It doesn't look like you are binding the parent testMethod to the child vue component (which you are doing with child --> grandchild with <grandchild :secondMethod="secondMethod". A method has to be bound to the component in order to have access. - Jayem163
I did in the html template. <div id='div'> <child :data1="data1" :testMethod="testMethod"></child> </div> Just now i saw a reply, advised to use the kebab case as a binding, I tested and it worked. I wanted to mark as answer and it is just gone. - Zaw Moe Lwin

1 Answers

0
votes

https://jsfiddle.net/uvet4frb/2/

PS. It is not my answer, the suggestion deleted by someone.

<div id='div'>
  <child :data1="data1" :test-Method="testMethod"></child>
</div>

https://vuejs.org/v2/guide/components-props.html

That means when you’re using in-DOM templates, camelCased prop names need to use their kebab-cased (hyphen-delimited) equivalents: