Vue 子组件调用父组件的所有方法

1、子组件通过使用this.emit(‘xxx’) (xxx:是你要调用的方法名,只要方法名不要后面的小括号)
3、父组件把方法名传给子组件,在子组件里调用这个方法
代码如下:
1、子组件通过使用this.$http://parent.xxx

父组件代码:
下面展示一些 `内联代码片`// An highlighted block
var foo = 'bar';

<template>
  <div>
//导入子组件名称标签
    <child></child>
  </div>
</template>
<script>
//导入子组件路径
  import child from '~/components/dam/child';
  export default {
    components: {
//激活子组件
      child
    },
    methods: {
//将要被调用的方法
      fatherMethod() {
        console.log('测试');
      }
    }
  };
</script>

子组件代码:

<template>
  <div>
    <button @click="childMethod()">点击</button>
  </div>
</template>
<script>
  export default {
    methods: {
      childMethod() {
//调用父组件方法
        this.$parent.fatherMethod();
      }
    }
  };
</script>

2、子组件通过使用this.$emit(‘xxx’)

父组件代码:

<template>
  <div>
//导入子组件名称标签,绑定方法名
    <child @fatherMethod="fatherMethod"></child>
  </div>
</template>
<script>
//导入子组件路径
  import child from '~/components/dam/child';
  export default {
    components: {
//激活子组件
      child
    },
    methods: {
//将要被调用的方法
      fatherMethod() {
        console.log('测试');
      }
    }
  };
</script>

子组件代码:

<template>
  <div>
    <button @click="childMethod()">点击</button>
  </div>
</template>
<script>
  export default {
    methods: {
      childMethod() {
//调用父组件的方法
        this.$emit('fatherMethod');
      }
    }
  };
</script>

3、父组件把方法名传给子组件,在子组件里调用这个方法

父组件代码:

<template>
  <div>
//导入子组件名称标签,并把方法名传给子组件
    <child :fatherMethod="fatherMethod"></child>
  </div>
</template>
<script>
//导入子组件路径
  import child from '~/components/dam/child';
  export default {
    components: {
//激活子组件
      child
    },
    methods: {
//将要被调用的方法
      fatherMethod() {
        console.log('测试');
      }
    }
  };
</script>

子组件代码:

<template>
  <div>
    <button @click="childMethod()">点击</button>
  </div>
</template>
<script>
  export default {
//设置props
    props: {
      fatherMethod: {
        type: Function,
        default: null
      }
    },
    methods: {
      childMethod() {
      //调用父组件的方法
        if (this.fatherMethod) {
          this.fatherMethod();
        }
      }
    }
  };
</script>

PS:三种方法,只有第一种方法是在路由下使用,使用时可以不用在父组件中间写 “” 、 “import child from ‘~/components/dam/child’;” 和 “components: {child },” ,第一个“”可以直接不用写,后面两个在使用路由情况下,会在路由里上;
后面两种方法在使用路由情况下未能触发父组件的方法(也许是我写的方法不对,大家直接可以尝试一下)。
还有就是“”这个不是标准的标签,同时它也是子组件的名字,也就是 child.vue

转载于:https://www.cnblogs.com/jin-zhe/p/9523782.html#commentform

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值