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实例外面,效果同上。

  • 相关阅读:
    复利计算-做汉堡,结对2.0
    复利计算-结对
    《构建之法》第四章读后感
    复利计算单元测试
    实验一 命令解释程序的编写
    《构建之法》前三章章读后感
    1.0 2.0 3.0复利计算器
    实验0:了解和熟悉操作系统
    学习进度条
    0302思考并回答一些问题
  • 原文地址:https://www.cnblogs.com/guobin-/p/13608603.html
Copyright © 2011-2022 走看看