2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Vue Composableからemitしたい時

Last updated at Posted at 2023-03-06

Vue2から3への以降でmixinをComposableにしていく時、そのまま置換するとComposableからemitしたくなる

一応emitを引数に渡せばできる

export default function useTest(emit: Function) {
  return {
    clicked() {
      // いろいろ処理
      emit("clicked", "arg1")
    }
  }
}

OptionsAPI

<script>
export default {
  onClick() {
    const {clicked} = useTest(this.$emit);
    clicked();
  }
}
</script>

CompositionAPI

<scipt setup lang="ts">
const emit = defineEmits();
const {clicked} = useTest(emit);

function onClick() {
  clicked();
}
</script>

でもこれだと定義したemit以外も呼べるので,機能だけ呼んでemitはコンポーネントでやるほうが良い

<scipt setup lang="ts">
const emit = defineEmits(["clicked"]);
const {clicked} = useTest();

function onClick() {
  clicked();
  emit("clicked");
}
</script>
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?