1、html中写法:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="app">
<ul>
<li v-for="item in students" @click="onLiClick(item)" :key="item.id">{{item.name}}</li>
</ul>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
new Vue({
//指定作用于那一个div
el: '#app',
//属性
data: {
students: [
{ id: 1, name: 'xiaoming', age: 18 },
{ id: 2, name: 'xiaoli', age: 20 }
]
},
methods: {
onLiClick(data) {
console.log(data.name);
}
}
});
</script>
</body>
</html>
2、vue文件中写法
<template>
<div class="hello">
<ul>
<li v-for="item in students" @click="onLiClick(item)" :key="item.id">{{ item.name }}</li>
</ul>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data() {
return {
students: [
{ id: 1, name: 'xiaoming', age: 18 },
{ id: 2, name: 'xiaoli', age: 20 }
]
}
},
methods: {
onLiClick(data) {
console.log(data.name);
}
}
}
</script>