最新学习vue在对computed的使用场景不是特别明白,直到看到这个例子。
当我修改第一行和第二行时,第三行就会发生改变。
改变前:
改变后:
代码:
- <form id="app" action="">
- <div>
- <label>姓
- <input type="text" placeholder="请输入你的姓" v-model="xing">
- </label>
- </div>
- <div>
- <label>名
- <input type="text" placeholder="请输入你的名" v-model="ming">
- </label>
- </div>
- <div>
- <label>姓名
- <input placeholder="请输入你的姓名" type="text" v-model="fullName">
- </label>
- </div>
- </form>
- new Vue({
- el: '#app',
- data: {
- xing: '王',
- ming:'小明'
- },
- computed:{
- fullName(){
- //比如这里添加更多的逻辑操作
- return this.xing+this.ming;
- }
- }
- });
思考总结:
我们知道methods里的方法需要人为主动触发,比如 :click,比如添加了某个商品,需要计算购物车总金额,我们定义这个方法为calcuPrice(),如果在methods里定义calcuPrice()就需要我们在所有添加商品的地方onClick时,或者修改商品个数时都要去调用calcuPrice()方法,但如果将calcPrice()放在computed里,只要某个变量发生了变化(比如存放商品的列表list)就会主动触发calcPrice()计算金额。这种情况下computed是不是非常有用!!
下面就是从一个项目里拷贝来的购物车相关代码:
- computed: {
- cartGoods () {
- return this.$store.state.cartGoods; //state里定义的cardGoods全局变量
- },
- //计算商品总价,这种操作就适合放在computed里面
- amount () {
- let cartGoods = this.$store.state.cartGoods;
- let result = 0;
- cartGoods.forEach(good =>{
- result += good.price * good.count;
- })
- return result;
- },
- //合计
- pay () {
- let result = this.amount - this.redPacket; //总价减去红包金额
- if (result >= 49) {
- this.needPostage = false;
- } else {
- this.needPostage = true;
- }
- if (this.needPostage) {
- result += this.postage;
- }
- return result;
- },
- },