简体   繁体   English

Vue - 将方法作为道具传递给孩子

[英]Vue - Passing method as prop to children

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

I've used Vue and was able to passed methods as props.我使用过 Vue 并且能够将方法作为道具传递。 In the code example, parent, child and grand child.在代码示例中,父、子和孙子。 Child can pass the method to grandChild, which both are declared via Vue.component. Child 可以将方法传递给 grandChild,它们都是通过 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.我是 Vuejs 新手,请解释是范围问题还是在创建导致子组件中未定义属性的组件时未定义 $root 方法。 PS. 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);

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

PS. PS。 It is not my answer, the suggestion deleted by someone.这不是我的答案,有人删除了该建议。

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

https://v2.vuejs.org/v2/guide/components-props.html https://v2.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:这意味着当您使用 in-DOM 模板时,camelCased 道具名称需要使用其 kebab 大小写(连字符分隔)等效项:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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