1

I have this simple example written in Vue.js.

// vue instance
var vm = new Vue({
    el: "#app",
    data: {
        matrix: ["", "", "", "", "", "", "", "", ""],
    },
    methods: {
        handleClick: function() {
            console.log("event triggered");
        }
    }
})
* {
  box-sizing: border-box;
}

#game-box {
  width: 150px;
  display: block;
  margin: 0px auto;
  padding: 0px;
  background: green;
}

.grid-item {
  float: left;
  width: 33.333%;
  height: 50px;
  background: yellow;
  border: 1px solid green;
  margin: 0px;
  text-align: center;
}
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app">
  <div id="game-box">
    <div v-for="(sign, index) in matrix" class="grid-item" @click="handleClick">
      {{ sign }}
    </div>
  </div>
</div>

Is there any way to send data with click event (for example the index of the element that was clicked) in order to be handled by the handleClick method doing something like this:

handleClick: function(index) {
    console.log(index);
}
1
  • 1
    @click="handleClick(index) should work, have you tried this way? working example jsfiddle.net/azs06/4ps1b4nk Commented Jan 26, 2017 at 22:07

2 Answers 2

4

The following snippet will pass index to your handleClick function.

handleClick(index)

// vue instance
var vm = new Vue({
    el: "#app",
    data: {
        matrix: ["", "", "", "", "", "", "", "", ""],
    },
    methods: {
        handleClick: function(i) {
            console.log("event triggered", i);
        }
    }
})
* {
  box-sizing: border-box;
}

#game-box {
  width: 150px;
  display: block;
  margin: 0px auto;
  padding: 0px;
  background: green;
}

.grid-item {
  float: left;
  width: 33.333%;
  height: 50px;
  background: yellow;
  border: 1px solid green;
  margin: 0px;
  text-align: center;
}
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app">
  <div id="game-box">
    <div v-for="(sign, index) in matrix" class="grid-item" @click="handleClick(index)">
      {{ sign }}
    </div>
  </div>
</div>

Sign up to request clarification or add additional context in comments.

2 Comments

The use of an arrow / anonymous function is unnecessary. A simple handleClick(index) will do.
Ah yep, I assumed it would call that function on load. Thanks!
2
// in view
@click='handleClick(data)'


// in logic
methods: {
handleClick(dataFromClick) => {
// do something with dataFromClick
}
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.