vue--子组件调用父组件的方法

在做VUE开发的时候,很多时候会遇到需要在子组件调用父组件的方法的时候,具体的实现方式有三种:

第一种:正规做法

示例:父组件(需要:@parentMethods="handleParentMethods")

<template>
   <editor id="editor" class="editor" @parentMethods="handleParentMethods"></editor>
</template>
<script>
export default {
  methods: {
    handleParentMethods: function (str) {
      alert(str)
    }
  }
}
</script>

子组件调用:

<template>
    <button @click="submit">提交</button>
</template>
<script>
export default {
  methods: {
    submit: function () {
      // 子组件中触发父组件方法parentMethods并传值123
      this.$emit('parentMethods', '123')
    }
  }
}
</script>

第二种:直接将父组件方法通过参数的形式进行传递

父组件:(需要::parentMethods="handleParentMethods")

<template>
    <editor id="editor" class="editor" :parentMethods="handleParentMethods"></editor>
</template>
<script>
export default {
  methods: {
    handleParentMethods: function (str) {
      alert(str)
    }
  }
}
</script>

子组件:

<template>
    <button @click="submit">提交</button>
</template>
<script>
export default {
  props: {
    parentMethods: {
      type: Function,
      default: function(){
          return "";
      }
    }
  },
  methods: {
    submit: function () {
      if (this.onsubmit) {
        this.parentMethods('123456');
      }
    }
  }
}
</script>

第三种:this.$parent.方法

示例:

this.$parent.parentMethods('123456');
posted @ 2018-10-16 09:58  帅到要去报警  阅读(279)  评论(0编辑  收藏  举报