v-on
作用:注册事件 = 添加监听 + 提供处理逻辑
语法:
v-on:事件名="内联语句"
v-on:事件名="methods中的函数名"
注意:" v-on:"可以替换为" @ "
v-on:click="XXX" --> @click="XXX"
demo:
v-on:事件名="内联语句"的demo:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- <script src="https://cdn.jsdelivr.net/npm/vue@2.7.16/dist/vue.js"></script> -->
</head>
<body>
<div id="app">
<button v-on:click="count--">-</button>
<span>{{count}}</span>
<button v-on:click="count++">+</button>
<!-- 可以赋值 -->
<!-- <button v-on:click="count=count+2">+</button> -->
</div>
<script src="js/vue.js"></script>
<script>
const app = new Vue({
//通过el配置选择器,指定Vue管理的是哪个盒子
el: '#app',
//通过data提供数据
data: {
count:100
}
})
</script>
</body>
</html>
页面效果图:
v-on:事件名="methods中的函数名"的demo:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- <script src="https://cdn.jsdelivr.net/npm/vue@2.7.16/dist/vue.js"></script> -->
</head>
<body>
<div id="app">
<button @click="fn">切换显示隐藏</button>
<h1 v-show="isShow">Demo</h1>
</div>
<script src="js/vue.js"></script>
<script>
const app = new Vue({
//通过el配置选择器,指定Vue管理的是哪个盒子
el: '#app',
//通过data提供数据
data: {
isShow:true
},
methods:{
fn(){
console.log('执行了fn')
}
}
})
</script>
</body>
</html>
页面效果:
demo2:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#app {
width: 500px;
height: 400px;
border: 2px solid #333;
padding: 20px;
border-radius: 8px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
h2 {
color: pink;
font-size: 24px;
margin-bottom: 20px;
}
button {
padding: 10px 20px;
font-size: 16px;
border: none;
border-radius: 4px;
background-color: pink;
color: black;
cursor: pointer;
margin-right: 10px;
transition: background-color 0.3s ease;
}
button:hover {
background-color: yellow;
}
</style>
<!-- <script src="https://cdn.jsdelivr.net/npm/vue@2.7.16/dist/vue.js"></script> -->
</head>
<body>
<div id="app">
<h2>自动售卖机</h2>
<button @click="buy(3)">可乐 3 元</button>
<button @click="buy(10)">咖啡 10 元</button>
<button @click="buy(5)">牛奶 5 元</button>
</div>
<script src="js/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
money: 100
},
methods: {
buy(price) {
console.log('消费了' + price + '元');
this.money -= price;
}
}
});
</script>
</body>
</html>