子组件 调用父组件方法

这篇文章中介绍了三种方法分别为:
1、子组件通过使用this.parent.xxx (xxx:是你要调用的方法名) 2、子组件通过使用this.emit('xxx') (xxx:是你要调用的方法名,只要方法名不要后面的小括号)
3、父组件把方法名传给子组件,在子组件里调用这个方法

代码如下:

1、子组件通过使用this.$parent.xxx
父组件代码:

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



原文地址:https://www.cnblogs.com/jinsuo/p/12523422.html