zoukankan      html  css  js  c++  java
  • 子组件调用父组件的方法

    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>

    2、通过在父组件中为子组件绑定父组件的方法的形式

    2.1、在父组件中为子组件绑定父组件的方法相关代码

    methods: {
        addComment (comment) {
          // unshift向数组的开始位置插入元素
          this.comments.unshift(comment)
        }
    }
    <!--在父组件中给子组件绑定父组件的方法-->
    <add @addComment="addComment"></add>

    2.2、在子组件中调用为子组件绑定的父组件的方法

    methods: {
        addFunc () {
          // 在子组件中调用父组件的为子组件绑定的方法
          this.$emit('addComment', {name: this.name, content: this.content})
        }
    }

    3、在父组件中通过$on为子组件绑定父组件的方法相关代码

    3.1、在父组件中使用某个组件

    <Header ref="header"></Header>

    3.2、在父组件中使用$on为子组件绑定方法

    mounted () {
        // 为ref="header"的组件绑定自定义方法,方法名为addTodo
        // this.addTodo为父组件中定义的方法
        this.$refs.header.$on('addTodo', this.addTodo)
    }

    3.3、在子组件中触发在父组件中被绑定的方法

    methods: {
        addFunc () {
          if (!this.name) {
            alert('请输入')
            return
          }
          // 在子组件中触发在父组件中被绑定的方法
          this.$emit('addTodo', {name: this.name, checked: false})
          this.name = null
        }
    }
  • 相关阅读:
    用Actionscript3.0编写的伪3D文字旋转
    iis权限设置
    SQL 不能通过IP正常连接终极解决方案
    创建一个非常简单的NHibernate的应用
    解决“System.Data.OracleClient需要Oracle客户端软件8.1.7或更高版本”
    详细讲解提高数据库查询效率的实用方法、外键关于性能
    解决ERRORORA12514:TNS:监听程序当前无法识别连接描述符中请求的服务
    session丢失问题
    Jquery AJAX WebService处理方式 demo
    DIV模拟弹出窗口(支持拖动)
  • 原文地址:https://www.cnblogs.com/liuyang-520/p/12545217.html
Copyright © 2011-2022 走看看