如何使用Vue.js中的click事件发送数据

时间:2017-01-26 21:56:36

标签: javascript vue.js vuejs2

我有这个用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>

有没有办法用click事件发送数据(例如被点击的元素的索引),以便由handleClick方法处理这样的事情:

handleClick: function(index) {
    console.log(index);
}

2 个答案:

答案 0 :(得分:4)

以下代码段会将索引传递给您的handleClick函数。

handleClick(index)

&#13;
&#13;
// vue instance
var vm = new Vue({
    el: "#app",
    data: {
        matrix: ["", "", "", "", "", "", "", "", ""],
    },
    methods: {
        handleClick: function(i) {
            console.log("event triggered", i);
        }
    }
})
&#13;
* {
  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;
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

// in view
@click='handleClick(data)'


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