zoukankan      html  css  js  c++  java
  • vue之父子组件执行对方的方法

    一、子组件执行父组件中的方法

    1、父组件将方法名传给子组件,子组件进行调用

    父组件中:

    <Vbutton typeBtn="success" :btnUserMethod="addOneUser" >添加用户</Vbutton> 
        methods: {
          addOneUser() {
    
            $('#addModal').modal('show')
          }
    }

    子组件中:

    <template>
    
      <button class="btn" :class="currentBtn" @click="handleClickParent">
    
        <slot>按钮</slot>
    
      </button>
    
    </template>
          props:{
            typeBtn:String,
            btnUserMethod:Function //验证类型接收父组件方法名
          },
    
         methods:{
            handleClickParent(){
              this.btnUserMethod(); //子组件调用父组件方法
            }
          },

    2、子组件里用$emit向父组件触发一个事件,父组件监听这个事件

    父组件中:

    <Vbutton typeBtn="success" :btnUserMethod="addOneUser" >添加用户</Vbutton> 
      methods: {
          addOneUser() {
    
            $('#addModal').modal('show')
          }
    }

    子组件中:

    <template>
    
      <button class="btn" :class="currentBtn" @click="handleClickParent">
    
        <slot>按钮</slot>
    
      </button>
    
    </template>
          methods:{
            handleClickParent(){
              this.$emit('addOneUser');  //这里还可以向父组件传参,只需要父组件函数有对应的形参即可
            }
          },
        }

    二、父组件执行子组件中的方法

     子组件:

    //子组件Vbutton 
    childMethod(){
              alert("我是子组件方法")
            }

    父组件:

    <template>
     <div>
         <button @click="parentClick">点击</button>
            <Vbutton ref="child" />         <!--使用组件标签-->
    </div>
    </template>
          parentClick() {
            this.$refs.child.childMethod("我是子组件里面的方法"); // 调用子组件的方法childMethod
      },

    (1)在子组件中写入相应的方法

    (2)在父组件中引入子组件

    (3) <Vbutton ref="mychild" /> 是在父组件中为子组件添加一个占位,ref="child"是子组件在父组件中的名字

    (4)在父组件的方法中调用子组件的方法,很重要   this.$refs.child.childMethod("我是子组件里面的方法");

  • 相关阅读:
    程序员的7中武器
    需要强化的知识
    微软中国联合小i推出MSN群Beta 不需任何插件
    XML Notepad 2006 v2.0
    Sandcastle August 2006 Community Technology Preview
    [推荐] TechNet 广播 SQL Server 2000完结篇
    《太空帝国 4》(Space Empires IV)以及 xxMod 英文版 中文版 TDM Mod 英文版 中文版
    IronPython 1.0 RC2 更新 1.0.60816
    Microsoft .NET Framework 3.0 RC1
    《Oracle Developer Suite 10g》(Oracle Developer Suite 10g)V10.1.2.0.2
  • 原文地址:https://www.cnblogs.com/shenjianping/p/11260397.html
Copyright © 2011-2022 走看看