我有这个用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);
}
答案 0 :(得分:4)
以下代码段会将索引传递给您的handleClick函数。
handleClick(index)
// 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;
答案 1 :(得分:1)
// in view
@click='handleClick(data)'
// in logic
methods: {
handleClick(dataFromClick) => {
// do something with dataFromClick
}
}