前言
在没有使用vue.js的时候,而使用JavaScript时我们将都是操作dom树来进行点击事件的操作,这样写起来是很麻烦,代码如下进行操作
<input type="button" id="show">
<script>
document.getElementById("show").onclick=function(ev){
alert("hello");
}
</script>
但是在vue中使用v-on就可以直接绑定事件进行操作,而且只要在methods里面写相对应的方法就能够实现,而操作事件就是JavaScript里面的一些事件。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>v-on指令</title>
</head>
<body>
<div id="app">
<--!提供v-on的事件绑定机制-->
<input type="button" :title="mytitle" v-on:click="show" value="按钮">
</div>
</body>
<script src="lib/vue.js"></script>
<script>
var vm = new Vue({
el:'#app',
data:{
mytitle:'我的标题',
},
methods:{
//这个methods里面包含了一些当前vue实例的可用方法
show: function () {
alert("hello word")
}
}
})
/* document.getElementById("show").οnclick=function (ev) {
alert("hello")
}*/
</script>
</html>
v-on的缩写符号是@
简单跑马灯
在vm实例中想要获取data或者methods里面的方法都要使用this. 数据属性名 或者this.方法名来进行访问。这里的this就是表示我们的new出来的vm实例对象
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>跑马灯</title>
</head>
<body>
<div id="app">
<input type="button" value="浪起来" @click="lang">
<input type="button" value="低调" @click="clear">
<h4>{{msg}}</h4>
</div>
</body>
<script src="lib/vue.js"></script>
<script>
var vm = new Vue({
el: '#app',
data: {
msg: "猥琐发育,别浪",
intervalId:null
},
methods: {
lang() {
if (this.intervalId!=null) return;
console.log(this.msg);
this.intervalId =setInterval(()=>{//获取头的第一个字符
var start = this.msg.substring(0, 1);
//获取到后面所有的字符
var end = this.msg.substring(1);
//重新拼接得到新的字符串 并重新赋值给this.msg
this.msg = end + start;},400);
// vm会监听直接的data的数据,只要data一改变他会立即
// 好处:程序员只要关心数据,不需要考虑如何重新渲染到页面
},
clear(){
clearInterval(this.intervalId);
this.intervalId=null;
}
}
})
</script>
</html>