Vue样式绑定方法
程序员文章站
2022-07-04 19:36:35
...
一、class的方法
// 方法一:对象方法
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<script src='./vue.js'></script>
<style media="screen">
.activated {
color: red;
}
</style>
</head>
<body>
<div id="app">
<div @click="handleDivClick" :class="{activated:isActivated}">hello world</div>
</div>
<script>
var vm = new Vue({
el: '#app',
data: {
isActivated: false
},
methods: {
handleDivClick: function() {
this.isActivated = !this.isActivated;
}
}
})
</script>
</body>
</html>
// 方法二:数组方法
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<script src='./vue.js'></script>
<style media="screen">
.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: {
isActivated: false,
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>
二、style的方法
// 方法一:对象方法
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<script src='./vue.js'></script>
<style media="screen">
.activated {
color: red;
}
</style>
</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>
// 方法二:数组方法
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<script src='./vue.js'></script>
<style media="screen">
.activated {
color: red;
}
</style>
</head>
<body>
<div id="app">
<div :style="[styleObj,{fontSize:'20px'}]" @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>
上一篇: 50个脑筋急转弯