<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="https://unpkg.com/vue@next"></script>
<style>
.transition {
transition: 1s background linear;
}
.orangered {
background-color: orangered;
}
.green {
background-color: green;
}
</style>
</head>
<body>
<div id="root"></div>
</body>
<script>
const app = Vue.createApp({
data() {
return {
myData: {
transition: true,
orangered: true,
green: false,
},
};
},
methods: {
handleClick() {
this.myData.orangered = !this.myData.orangered;
this.myData.green = !this.myData.green;
},
},
template: `
<h1 v-bind:class="myData">hello world</h1>
<button @click="handleClick">切换</button>
`,
});
const vm = app.mount("#root");
</script>
</html>
另一种方式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="https://unpkg.com/vue@next"></script>
<style>
.transition {
transition: 1s background linear;
}
</style>
</head>
<body>
<div id="root"></div>
</body>
<script>
const app = Vue.createApp({
data() {
return {
styleObj: {
backgroundColor: "red",
},
};
},
methods: {
handleClick() {
if (this.styleObj.backgroundColor === "red") {
this.styleObj.backgroundColor = "green";
} else {
this.styleObj.backgroundColor= "red";
}
},
},
template: `
<h1 class="transition" :style="styleObj">hello world</h1>
<button @click="handleClick">点击</button>
`,
});
const vm = app.mount("#root");
</script>
</html>