Vue 中的事件绑定
案例:点击 Hello World ,从黑变红,再次点击,从红变黑...
通过 class 来实现 页面效果的变更
方法一:(通过对象)对象绑定
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vue 中的事件绑定</title>
<script src="./vue.js"></script>
<style>
.activated{color: red;}
</style>
</head>
<body>
<div id="app">
<div @click="handleDivClick"
:class="{activated:isActivated}">
Hello World
</div>
<script>
var vm = new Vue({
el:"#app",
data:{isActivated:false},
methods: {
handleDivClick:function(){
this.isActivated = !this.isActivated;
}
}
})
</script>
</body>
</html>
输出:
点击
再点击
方法二:(通过数组)将 activated 放置在数组中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vue 中的事件绑定</title>
<script src="./vue.js"></script>
<style>
.activated{color: red;}
</style>
</head>
<body>
<div id="app">
<div @click="handleDivClick"
:class="[activated]">
Hello World
</div>
</div>
<script>
var vm = new Vue({
el:"#app",
data:{
activated:""
},
methods: {
handleDivClick:function(){
if(this.activated === "activated"){
this.activated = "";
}else{
this.activated="activated";
//this.activated = this.activated === "activated" ? "" : "activated"
}
}
}
})
</script>
</body>
</html>
补充:
动态的给一个DOM元素添加或删除不同的类,从而实现页面效果的变更
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vue 中的事件绑定</title>
<script src="./vue.js"></script>
<style>
.activated{color: red;}
</style>
</head>
<body>
<div id="app">
<div @click="handleDivClick"
:class="[activated,activatedOne]">
Hello World
</div>
</div>
<script>
var vm = new Vue({
el:"#app",
data:{
activated:""
activatedOne:"activated-one"
},
methods: {
handleDivClick:function(){
if(this.activated === "activated"){
this.activated = "";
}else{
this.activated="activated";
//this.activated = this.activated === "activated" ? "" : "activated"
}
}
}
})
</script>
</body>
</html>
输出:类从 activated 变更为 activated-one
通过 style 来实现 页面效果的变更
方法一:(通过对象)第一次为 black,故显示为黑色,当等于 black 则返回 red,则第二次显示红色,返回black...达到颜色变更的目的
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vue 中的事件绑定</title>
<script src="./vue.js"></script>
</head>
<body>
<div id="app">
<div :style="styleobj" @click="handleDivClick">
Hello World
</div>
</div>
<script>
var vm = new Vue({
el:"#app",
data:{
styleobj:{
color:"black"
}
},
methods: {
handleDivClick:function() {
this.styleobj.color = this.styleobj.color ==="black"?"red" :"black" ;
}
}
})
</script>
</body>
</html>
输出:
点击
再点击
方法二:(通过数组)(只需将 styleobj 放入数组即可)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vue 中的事件绑定</title>
<script src="./vue.js"></script>
</head>
<body>
<div id="app">
<div :style="[styleobj]" @click="handleDivClick">
Hello World
</div>
</div>
<script>
var vm = new Vue({
el:"#app",
data:{
styleobj:{
color:"black"
}
},
methods: {
handleDivClick:function() {
this.styleobj.color = this.styleobj.color ==="black"?"red" :"black" ;
}
}
})
</script>
</body>
</html>
如果 style 后面跟着一个数组,DIV 的样式由数组里的 对象 所决定,这个对象有 color:"black";所以 DIV 显示黑色,第一次为 black,故显示为黑色,当等于 black 则返回 red,则第二次显示红色,返回black...达到颜色变更的目的。