使用vue的v-model数据绑定之setinterval()改变数据后不更新视图

造成这一现象的原因是由于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>

 

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值