1. 程式人生 > >vue中子元件觸發父元件的方法

vue中子元件觸發父元件的方法

方法一:

子元件:

`<template>
        <button @click="submit">提交</button>
    </template>
    <script>
    export default {
      methods: {
        submit: function () {
          // 子元件中觸發父元件方法ee並傳值cc12345
          this.$emit('ee', 'cc12345')
        }
      }
    }
    </script>`

父元件:

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

方法二:

子元件:

<template>
    <button @click="submit">提交</button>
</template>
<script>
export default {
  props: {
    onsubmit: {
      type: Function,
      default: null
    }
  },
  methods: {
    submit: function () {
      if (this.onsubmit) {
        this.onsubmit(‘cc12345’)
      }
    }
  }
}
</script>

父元件:

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