目录
接下来学习@click
例题:修改背景颜色
先看以下例题是回顾vue的用法
-
<body><div id="box">{{myname}} - {{myage}}</div><script>var vm = new Vue({el:"#box",data:{myname:"lyx",myage:26}})</script></body>
- 运行结果如下:vue对象被挂载到vm实例上
- 通过在控制台直接vm.属性名修改
接下来学习@click
可以看到@click形式是对v-on:click的简写
<a v-on:click="doSomething"> ... </a><!-- 简写 -->
<a @click="doSomething"> ... </a>
vue对象的el、data、methods属性
<!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="../vue/vue.js"></script>
</head><body><div id="box">{{myname}} - {{myage}}<button @click="handleChange()">点我控制台输出</button></div><script>var vm = new Vue({el:"#box",data:{myname:"lyx",myage:26},methods:{handleChange(){console.log("哈哈哈哈哈哈哈哈哈");}}//定义所有事件方法})</script></body></html>
在handleChange()方法里面对myname和myage的值进行修改,点击button页面刷新可以看到:
<div id="box">{{myname}} - {{myage}}<button @click="handleChange()">click me</button></div><script>var vm = new Vue({el:"#box",data:{myname:"lyx",myage:26},methods:{handleChange(){console.log("哈哈哈哈哈哈哈哈哈");vm.myname = "xmq";vm.myage = 22;}}//定义所有事件方法})</script>
通过this.myname、this.myage来修改值
运行结果如下:
例题:修改背景颜色
<!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="../vue/vue.js"></script><style>.bgRed {background: #da3939;height: 100px;width: 100px;}.bgBlue {background: #4dddd1;height: 100px;width: 100px;}</style>
</head><body><div id="box">{{myname}} - {{myage}}<button @click="handleChange()">click me</button><div :class="whichcolor"></div></div><script>new Vue({el: "#box",data: {myname: "lyx",myage: 26,whichcolor: "bgRed"},methods: {handleChange(t) {console.log("哈哈哈哈哈哈哈哈哈", this);this.myname = "xmq";this.myage = 22;this.whichcolor = "bgBlue";}}//定义所有事件方法})</script></body></html>
例题:反复点击button按钮,可以不断切换背景颜色
效果如下:
<!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="../vue/vue.js"></script><style>.bgRed {background: #da3939;height: 100px;width: 100px;}.bgBlue {background: #4dddd1;height: 100px;width: 100px;}</style>
</head><body><div id="box">{{myname}} - {{myage}}<button @click="handleChange()">click me</button><div :class="whichcolor"></div><br /><div :class="isColor?'bgRed':'bgBlue'"></div></div><script>new Vue({el: "#box",data: {myname: "lyx",myage: 26,whichcolor: "bgRed",isColor: true},methods: {handleChange(t) {console.log("哈哈哈哈哈哈哈哈哈");this.myname = "xmq";this.myage = 22;this.whichcolor = "bgBlue";this.isColor = !this.isColor;}}//定义所有事件方法})</script></body></html>