[英]Watch Property Doesn't work in Vuejs
I started to learn Vuejs, in the middle of a job I tried to test the Watch property but it doesn't work for me, can you tell what's wrong with the below code? 我开始学习Vuejs,在工作的中间,我尝试测试Watch属性,但对我而言不起作用,您能告诉我下面的代码有什么问题吗?
<div id="k2c">
Kilometers : <input v-model= "Kilometers">
Meters : <input v-model = "Meters">
</div>
<script type="text/javascript">
var vr = new Vue({
el:'#k2c',
data:{
Kilometers: 0;
Meters : 0;
},
methods:{
},
computed:{
},
watch : {
Kilometers : function(val){
this.Kilometers = val;
this.Meters = val * 1000;
},
Meters : function(val){
this.Kilometers = val / 1000;
this.Meters = val;
}
}
});
</script>
You are mutating the properties inside their watchers. 您正在变异其观察者内部的属性。 Don't, it is not necessary.
不需要,没有必要。 Apart from it, you had other problems (see comments below).
除此之外,您还有其他问题(请参阅下面的评论)。
Recommended reading: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Basics 推荐阅读: https : //developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Basics
<script src="https://unpkg.com/vue"></script> <div id="k2c"> Kilometers : <input v-model="Kilometers"> Meters : <input v-model="Meters"> </div> <script> var vr = new Vue({ el: '#k2c', data: { Kilometers: 0, // replaced ; with , Meters: 0 // removed ; here }, methods: { }, computed: {}, watch: { Kilometers: function(val) { //this.Kilometers = val; // commented out this line, you should remove it this.Meters = val * 1000; }, Meters: function(val) { this.Kilometers = val / 1000; //this.Meters = val; // commented out this line, you should remove it } } }); </script>
Note: Your two computed properties have a cyclic dependency (changing one changes the other and vice-versa). 注意:您的两个计算属性具有循环依赖性(改变一个改变另一个,反之亦然)。 Currently this is not a problem because their values are converging .
目前这不是问题,因为它们的值正在收敛 。 If this didn't happen, you'd get a stackoverflow error.
如果这种情况没有发生,则会出现stackoverflow错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.