一、定义样式
<style> .blueBack { background-color: blue; } .yellowBack { background-color: yellow; } </style>
二、定义两个按钮,一个div
<div id="vueFirst"> <div :class="backColor">{{info}}</div> <hr> <input type="button" value="变黄" @click="changeColorToYellow"></input> <input type="button" value="变蓝" @click="changeColorToBlue"></input> </div>
三、添加click事件
<script type="text/javascript" src="js/vue.js"></script>
<script type="text/javascript"> var vm = new Vue({ el: "#vueFirst", data: { info: "hello world", backColor: "blueBack" }, methods: { changeColorToYellow() { this.backColor = "yellowBack" }, changeColorToBlue() { this.backColor = "blueBack" } } })
完整代码如下:
<html> <head> <style> .blueBack { background-color: blue; } .yellowBack { background-color: yellow; } </style> </head> <body> <div id="vueFirst"> <div :class="backColor">{{info}}</div> <hr> <input type="button" value="变黄" @click="changeColorToYellow"></input> <input type="button" value="变蓝" @click="changeColorToBlue"></input> </div> <script type="text/javascript" src="js/vue.js"></script> <script type="text/javascript"> var vm = new Vue({ el: "#vueFirst", data: { info: "hello world", backColor: "blueBack" }, methods: { changeColorToYellow() { this.backColor = "yellowBack" }, changeColorToBlue() { this.backColor = "blueBack" } } }) </script> </body> </html>