3.7 computed:动态计算组件内变量
组件内变量通常都定义在data里面,但有一种变量,是动态计算的:
例如这个组件里的例子:
export default{ name:"Study", data(){ return{ user:"", } }, created:function(){ }, mounted:function(){ }, methods:{ }, computed:{ id(){ /* 从url里面取出参数id的值,例如localhost/test?id=12325,下面的id值就是12325 */ let id=this.$route.query.id; if( ! id){ id=sessionStorage.getItem("chapterId"); } return id; }, code(){ let code=this.$route.query.code; code="010100"; return code; }, },}
这里的id和code就是需要使用的时候,马上调用id()和code()这两个函数算出来。假设它的template部分有这样的代码:
<template> <div> id是{{id}},code是{{code}}, </div></template>
第2行可以直接把id和code当作变量使用,注意这个时候在data中不能再定义id和code,否则会出语法错误。
下面是一个computed的应用:
有一些数据之间有关联,A数据的变动会影响到B数据,例如
1.购物车数据和总价
2.数据查询到的数据数量和要分页的数量(假设每页显示20条数据)
这就要用到computed方法,下面是一个购物车的例子,products是商品,cart是购物车,其中cartCount和cartTotal这两个数据,分别表示共几件商品,总价是多少,就是即刻计算出来的,通过computed里面两个函数计算出来,不需要在data中定义:
export default{ data(){ return{ products:[ { name:"苹果",price:5 }, { name:"香蕉",price:3 }, { name:"橙子",price:4 } ] ,cart:[], inputQty:1 } ; }, computed:{ cartCount(){ let count=0; for(let i=0;i < this.cart.length;i++){ count+=this.cart[i].qty; } return count; }, cartTotal(){ let total=0; for(let i=0;i < this.cart.length;i++){ total+=this.cart[i].qty*this.cart[i].price; } return total; } }, methods:{ addToCart(product, qty){ let itemIndex=this .cart.findIndex(item=>item.name===product.name); if(itemIndex >= 0){ this.cart[itemIndex].qty+=qty; } else{ this.cart.push({ name:product.name, price:product.price, qty:qty }); } } }}
然后是template部分:
<template> <div> <table> <thead> <tr> <th>商品名称</th> <th>单价(元)</th> <th>数量</th> <th>小计(元)</th> </tr> </thead> <tbody> <tr v-for="(item, index) in cart" :key="index"> <td>{{item.name}}</td> <td>{{item.price}}</td> <td>{{item.qty}}</td> <td>{{item.qty*item.price}}</td> </tr> </tbody> </table> <div class="cart-footer"> <div class="add-to-cart"> <label for="quantity"> 数量: </label> <input type="number" id="quantity" v-model.number="inputQty"/> <button @click="addToCart(product, inputQty)">加入购物车</button> </div> <span>共{{cartCount}}件商品</span> <span>总价:¥{{cartTotal}}</span> </div> </div></template>
想办法,给这个购物车增加一个减少商品数量的函数