造成这一现象的原因是由于this指向在setInterval间歇调用时发生了变化,注意v-model绑定数据是字符串值,如果要使用数值要进行相应的处理,先使用parseInt()等进行数据类型转换,由于定时时候this指向改变了,不再指向实例。所以在进入定时前进行保存。就可以正常工作了。

new Vue({
		el:"#app",
		data(){
			return{
				msg:0,
				msg1:0,
				msg2:0,
				timer:null
			}
		},
		methods:{
			change(){
				clearInterval(this.timer);
				let one=parseInt(this.msg);
				let two=parseInt(this.msg1);
				let _this=this;
				this.timer=setInterval(function(){
					if (one<two) {
						one+=1;
						_this.msg2=one;	
					}else if(one==two){
						clearInterval(_this.timer);
						alert("数据变化到目标值");
					}else{
						one-=1;
						_this.msg2=one;	
					}
				},100)
			}
		}
	})

效果如下所示:

 

 

 

附录:完整代码

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>计数器</title>
	<script src="vue.js"></script>
	<style>
		*{
			padding: 0;
			margin:0;
		}
		section{
			height: 300px;
			background-color: rgb(34,48,74);
			color: #bbb;
		}
		div{
			margin:0 auto;
			text-align: center;
		}
		span{
			display: inline-block;
			width: 280px;
			height: 280px;
			background-color: #000;
			color: rgb(120,203,255);
			font-size: 126px;
			text-align: center;
			line-height: 280px;
			margin:2px 10px;
		}
		.main{
			width: 100%;
			height: 100%;
			display: inline-block;
		}
		.controls{
			text-align: center;
			margin:1px auto;
		}
		#button{
			padding: 5px;
			margin-top: 2px;
			background-color: orange;
		}
	</style>
</head>
<body>
	<div id="app">
		<section>
			<div class="main">
				<span>{{msg}}</span>
				<span>{{msg1}}</span>
				<span ref='vals'>{{msg2}}</span>
			</div>
		</section>
		<section class="controls">
			当前数: <input type="text" placeholder="请输入当前数" v-model="msg"><br>
			目标数: <input type="text" placeholder="请输入目标数" v-model="msg1"><br>
			运动:  <input type="button" value="点击从当前数字到目标数字" id="button" v-on:click="change">
		</section>
	</div>
</body>
<script>
	new Vue({
		el:"#app",
		data(){
			return{
				msg:0,
				msg1:0,
				msg2:0,
				timer:null
			}
		},
		methods:{
			change(){
				clearInterval(this.timer);
				let one=parseInt(this.msg);
				let two=parseInt(this.msg1);
				let _this=this;
				this.timer=setInterval(function(){
					if (one<two) {
						one+=1;
						_this.msg2=one;	
					}else if(one==two){
						clearInterval(_this.timer);
						alert("数据变化到目标值");
					}else{
						one-=1;
						_this.msg2=one;	
					}
				},100)
			}
		},
		watch:{
			msg:{
				deep:true,
				handler:function(newV,oldV){

				}
			}
		}
	})
</script>
</html>

 

 

Logo

前往低代码交流专区

更多推荐