zoukankan      html  css  js  c++  java
  • 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实例外面,效果同上。

  • 相关阅读:
    bzoj1297: [SCOI2009]迷路
    bzoj1875: [SDOI2009]HH去散步
    bzoj2466: [中山市选2009]树
    bzoj1770: [Usaco2009 Nov]lights 燈
    BZOJ 1965: [Ahoi2005]SHUFFLE 洗牌( 数论 )
    BZOJ 1004: [HNOI2008]Cards( 置换群 + burnside引理 + 背包dp + 乘法逆元 )
    BZOJ 1006: [HNOI2008]神奇的国度( MCS )
    BZOJ 1925: [Sdoi2010]地精部落( dp )
    BestCoder Round #57 (div.2)
    BZOJ 1216: [HNOI2003]操作系统( 优先队列 )
  • 原文地址:https://www.cnblogs.com/guobin-/p/13608603.html
Copyright © 2011-2022 走看看