watch的使用(以卖座后管系统为例-VUE)

2019-10-19

  1. 监听路由
watch: {
  $route(newRoute,oldRoute) {
    // todo
  }
}
//实例
let vm = new Vue({
 el: "#app",
 data: {},
 router,
 watch: {
  '$route.path': function (newVal, oldVal) {
   if (newVal === '/login') {
    console.log('欢迎进入登录页面');
   }
   if (newVal === '/register') {
    console.log('欢迎进入注册页面');
   }
  }
 }
})
watch监听路由.png
  1. 深层监听
watch:{
      childrens:{
        handler:function(val,oldval){
          console.log(val.name)
        },
        deep:true//对象内部的属性监听,也叫深度监听
      },
 }

  1. 立即执行
 poster: {
 handler(newName, oldName) {
   // ...
 },
 immediate: true
  }

Vue.js 简单购物车-(例子)

//html文件----------------------------------------------------------------------------------------------------------------------
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
    <table>
    <tr>
        <th>序号</th>
        <th>商品名称</th>
        <th>商品价格</th>
        <th>购买数量</th>
        <th>操作</th>
    </tr>
    <tr v-for="iphone in Ip_Json">
        <td>{{ iphone.id }}</td>
        <td>{{ iphone.name }}</td>
        <td>{{ iphone.price }}</td>
        <td>
        <button v-bind:disabled="iphone.count === 0" v-on:click="iphone.count-=1">-</button>
        {{ iphone.count }}
        <button v-on:click="iphone.count+=1">+</button>
        </td>
        <td>
        <button v-on:click="iphone.count=0">移除</button>
        </td>
    </tr>
    </table>
    总价:${{totalPrice()}}
</div>

//css文件----------------------------------------------------------------------------------------------------------------------
table {
    border: 1px solid black;
}
table {
    width: 100%;
}

th {
    height: 50px;
}
th, td {
    border-bottom: 1px solid #ddd;
}
//js文件
var app = new Vue({
  el: '#app',
  data: {
    Ip_Json: [{
      id: 1,
      name: 'iphone 8',
      price: 5099,
      count: 1
    },
              {
                id: 2,
                name: 'iphone xs',
                price: 8699,
                count: 1
              },
              {
                id: 3,
                name: 'iphone xr',
                price: 6499,
                count: 1
              }]
  },
  methods:{
    totalPrice : function(){
      var totalP = 0;
      for (var i = 0,len = this.Ip_Json.length;i<len;i++) {
        totalP+=this.Ip_Json[i].price*this.Ip_Json[i].count;
      }
      return totalP;
    }
  }
})
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容