vue父子组件之间方法调用

子组件调用父组件方法

子组件调用父组件方法主要有以下3种:

  • 在子组件中通过this.$parent.event来调用父组件的方法

    • 父组件

      	hasCancleBtn(){
              console.log('父组件')
          },
      
    • 子组件

      this.$parent.hasCancleBtn();
      
  • 父组件中将方法作为属性传入子组件,在子组件里props申明后直接调用这个方法即可

    • 父组件

      <children :hasCancleBtn="hasCancleBtn"></children>
      
      hasCancleBtn(){
      	console.log('父组件')
      }
      
    • 子组件

      <div @click="hasCancleBtn"></div>
      
      export default {
       props: {
          hasCancleBtn: {
            type: Function,
            default: null,
          }
        }
      }
      
  • 子组件中用$emit向父组件触发一个事件

    • 父组件

      <children @has-cancle-btn="hasCancleBtn"></children>
      

      此处如果像上种方法用驼峰命名在编译时可能会出错,所以最好使用 ’- '连接命名。

      hasCancleBtn(){
      	console.log('父组件')
      }
      
    • 子组件

      <div  @click="$emit('has-cancle-btn')"></div>
      

父组件调用子组件方法

  • 通过ref直接调用子组件的方法

    • 父组件

      <children ref="child"></children>
      
      mounted(){
      	this.$refs.child.getDetail();
      }
      
    • 子组件

      <div>子组件</div>
      
      mounted(){
      	getDetail(){
      		console.log('子组件')
      	}
      }
      
  • 通过组件的$emit$on方法

    • 父组件

      <children ref="child"></children>
      
      mounted(){
      	this.$refs.child.$emit("getDetail")    //子组件$on中的名字
      }
      
    • 子组件

      <div>子组件</div>
      
      mounted() {
          this.$nextTick(function() {
              this.$on('getDetail', function() {
                  console.log('子组件');
              });
          });
       }