Vue.js框架:事件处理(四)

一、简单应用

  1、使用methods定义方法进行调用:

  js代码:

var vm=new Vue({
  el:"#test",
  data:{
    message:"测试",
    count:0
  },
  methods:{
    addCount:function()
    {
      return this.count++;
    }
  }
}) 

  页面代码:

<div id="test">
    <button @click="addCount()">
        增加{{ count }}
    </button>
</div>

  结果截图:

  

  

  2、除去调用methods中的方法之外,也可以直接在click事件中进行操作:

  js代码:

var vm=new Vue({
  el:"#test",
  data:{
    message:"测试",
    count:0
  }
}) 

  页面代码:

<div id="test">
    <button @click="count++">
        增加{{ count }}
    </button>
</div>

  结果截图同上。

二、监听属性

  监听属性watch,通过设置监听属性来响应页面中的数据变化。

  js代码:

var vm=new Vue({
  el:"#test",
  data:{
    message:"测试",
    count:0,
    total:0,
    text:''
  },
  methods:{
    addCount:function()
    {
      return this.count++;
    },
    reduceCount()
    {
      if(this.count>0)
        return this.count--;
      else
        alert("当前数量已无法减少");
    }
  },
  watch:{
    count:function(val)
    {
      this.count=val;
      this.total=this.count*200;
    }
  }
});
vm.$watch('count',function(newVal,oldVal){
    if(newVal>oldVal)
      vm.text='您新增了'+(newVal-oldVal)+'件商品,现在选购数量为:'+newVal+',总价格为:'+vm.total;
    else if(newVal<oldVal)
      vm.text='您取消了'+(oldVal-newVal)+'件商品,现在选购数量为:'+newVal+',总价格为:'+vm.total;
})

  页面代码:

<div id="test">
    购买数量:
    <button @click="reduceCount()">
        -
    </button>
    <input type="text" v-model="count" />
    <button @click="addCount()">
        +
    </button>
    <br />
    购物总价:
    <span>{{ total }}(元)</span>
    <hr />
    <span>{{ text }}</span>
</div>

  结果截图:

  

  使用watch可以监听购买数量count,从而使购买总价totalcount发生改变时触发监听中的事件,从而跟随发生变化。

  vm.$watch是用在Vue实例外面,效果同上。

原文地址:https://www.cnblogs.com/guobin-/p/13608603.html