[Vue]侦听属性watch(十)

watch

  • 用于侦听变量的变化,然后进行相应的处理
  • 尽量不使用watch使用computed代替

示例源代码

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1.0">
  <script src="https://unpkg.com/vue/dist/vue.js"></script>
  <title>hellovue</title>
</head>
<body>
<div id="myApp">
  今天是3月3日发卖的任天堂新一代主机Switch的价格是:{{price}}日元,含税价格为:{{priceInTax}} 日元,折合人民币为:{{priceChinaRMB}}元。
  <button @click="btnClick(10000)">加价10000日元</button>
</div>
<script>
  var myApp = new Vue({
    /*绑定标签的id*/
    el: '#myApp',
    /*标签上绑定初始的数据*/
    data: {
      price: 29980,
      priceInTax: 0,
      priceChinaRMB: 0,
    },
    watch: {
      price: function (newVal, oldVal) {
        console.log(newVal, oldVal)
        this.priceInTax = Math.round(this.price * 1.08);
        this.priceChinaRMB = Math.round(this.priceInTax / 16.75);
      },
    },
    methods: {
      btnClick: function (newPrice) {
        this.price += newPrice;
      },
    },
  });
</script>
</body>
</html>

END

posted @ 2020-03-06 17:46  LeoShi2020  阅读(185)  评论(0编辑  收藏  举报