50
33

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 5 years have passed since last update.

【Vue】パラメータ付き$emitのハンドラに追加で引数を与える

Last updated at Posted at 2018-10-02

タイトルの通り

v-forのindexを追加で渡したかった。

以下で出来た。

{parent.vue}
<template>
  <div v-for="(item, index) in list" :key=index>
    <child :item='item' @emitting='emitted($event, index)'/>
  </div>
</template>

<script>
export default {
  ...
  methods: {
    emitted: function (eventArgs, index) {
      console.log(index, eventArgs)
    }
  },
  ...
}
</script>
{child.vue}
<template>
  <div @click='temp'>{{item}}</div>
</template>

<script>
export default {
  props:['item'],
  methods: {
    temp: function () {
      this.$emit('emitting', {item1: 'event' item2: 'args'})
    }
  }
}
</script>

2つ以上イベント引数があった場合の、2つ目以降の取得方法は不明。
1つのObjectにまとめることで回避。

うまく見つけられなかったのだけどアンチパターンなのだろうか

追記

コメントにて指摘のあった、emitを用いない方法

{ parent.vue }
<template>
  <div>
    <div v-for="(elm, idx) in list" :key="idx">
      <child :item="elm" :func="func(idx)"></child>
    </div>
  </div>
</template>

<script>
import Child from './Child'
export default {
  components: {
    Child
  },
  methods: {
    func: idx => (arg1, arg2) => {
      console.log(idx, arg1, arg2)
    }
  },
  data() {
    return {
      list: ['aa', 'ss', 'dd']
    }
  }
}
</script>
{child.vue}
<template>
  <v-btn @click="clicked">
    {{ item }}
  </v-btn>
</template>

<script>
export default {
  props: [ 'item', 'func' ],
  methods: {
    clicked: function() {
      this.func(this.state1, this.state2)
    }
  },
  data() {
    return {
      state1: 'ww',
      state2: 'qq'
    }
  }
}
</script>

50
33
2

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
50
33

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?