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

    vue子组件,调用父组件中有三种方法哈!下面我们一起来讲解。
    第一种使用 直接在子组件中通过this.$parent.父组件中的方法。来调用父组件的方法
    第一种的缺点是不能够传递参数哈。它只能够调用方法。

    子组件.vue
    <template>
        <div @click="fa">
            我是子组件
        </div>
    </template>
    
    <script>
        export default {
            methods:{
                fa(){
                    // 第一种 直接在子组件中通过this.$parent.父组件中的方法  来调用父组件的方法
                   this.$parent.fatherMethod('op');//父组件中有这一个方法fatherMethod     
                }
            }
        }
    </script>
    
    父组件.vue
     methods:{
                fatherMethod(){
                    console.log("被子组件触发了")
                }
     }
    
    

    第二种

    方法是在子组件里用$emit向父组件触发一个事件,父组件监听这个事件就行了 可以传递参数

    第三种

    子组件.vue
    <template>
        <div @click="mychild()">
            我是子组件
        </div>
    </template>
    
    <script>
        export default {
            props: {
                say: {
                    type: Function,
                    default: null
                }
            },
            methods:{
                    // 第三种是父组件把方法传入子组件中,在子组件里直接调用这个方法
                    mychild(){
                        if (this.say) {
                            this.say();
                        }
                    }
            }
        }
    </script>
    
    父组件
    <zidiaoyongfa :say="say"></zidiaoyongfa>
    
     say(){
          console.log("haha  我要说话")
      }
    
  • 相关阅读:
    scanf使用尿性
    System : Assembly Programming
    Biology 03: Cardiovascular
    remove the smallest element from a linkedlist
    Relativity 04: CH4CH5
    Relativity 03: Space and Time in Classical Mechanics
    146 __str__和__repr__
    145 __init__和__new__
    144 __call__
    143 __doc__
  • 原文地址:https://www.cnblogs.com/IwishIcould/p/12459849.html
Copyright © 2011-2022 走看看