子组件调用父组件的方法

1、通过父组件向子组件传Function类型的参数的形式

1.1、父组件向子组件传参的相关代码

methods: {
    addComment (comment) {
      // unshift向数组的开始位置插入元素
      this.comments.unshift(comment)
    }
}
<!--父组件向子组件传Function类型的参数-->
<add :addComment="addComment"></add>

1.2、子组件接收父组件Function类型的传参并调用该Function

<script>
export default {
  // 通过属性名或者属性名和属性类型的方式都可以接收Function类型的传参
  // props: ['addComment'],
  props: {
    addComment: Function
  },
  data () {
    return {
      name: null,
      content: null
    }
  },
  methods: {
    addFunc () {
      // 在子组件中调用父组件的Function类型的传参
      this.addComment({name: this.name, content: this.content})
    }
  }
}
</script>

猜你喜欢

转载自www.cnblogs.com/liuyang-520/p/12545217.html
今日推荐