Watch Property在Vuejs中不起作用

时间:2018-03-14 15:31:19

标签: javascript vue.js frameworks vuejs2 frontend

我开始学习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>

1 个答案:

答案 0 :(得分:2)

您正在改变观察者内部的属性。不,没有必要。除此之外,您还有其他问题(请参阅下面的评论)。

推荐阅读: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>

注意:您的两个计算属性具有循环依赖关系(更改一个会更改另一个,反之亦然)。目前这不是问题,因为它们的值是收敛。如果没有发生这种情况,您将收到堆栈溢出错误。