Vue2,Vue3 computed计算属性用法

计算属性就是当依赖的属性的值发生变化的时候,才会触发他的更改,如果依赖的值,不发生变化的时候,使用的是缓存中的属性值。

computed购物车案例

1.Vue2版

<template>
  <div>
   
  <div>
    <input v-model="keyword"/>  
    <table>
      <thead>
        <tr>
          <th>商品名称</th>
          <th>价格</th>
          <th>数量</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(product, index) in sousuo" :key="index">
          <td>{{ product.name }}</td>
          <td>{{ product.price }}</td>
          <td><button @click="product.quantity--">-</button>{{ product.quantity }}<button @click="product.quantity++">+</button></td>
          <td>
            <button @click="deleteProduct(index)">删除</button>
          </td>
        </tr>
      </tbody>
      
    </table>
    总价:{{getsum }}
  </div>
</div>
</template>

<script>
import { computed } from 'vue';
export default {
  data() {
    return {
      products: [
        { name: '商品1', price: 10, quantity: 5 },
        { name: '商品2', price: 20, quantity: 3 },
        { name: '商品3', price: 15, quantity: 2 }
      ],
      sum:0,
      keyword:''
    };
  },
  methods: {
    deleteProduct(index) {
      this.products.splice(index, 1);
    }
  },
  computed:{
    getsum() {
      const sum= this.sousuo.reduce((prev, next) => {
        return prev + next.price * next.quantity;
      }, 0);
      return sum
    },

    sousuo(){
      return this.products.filter(product=>product.name.includes(this.keyword))
    },

  },

  
  
};

</script>

<style>

</style>

效果图如下:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

2.Vue3+ts版
功能和Vue2版一样

<template>
  <div>
    <div>
        <p class="sou">搜索框在此:<input v-model="keyword" border:1px/> </p> 
       
    <table>
      <thead>
        <tr>
          <th>商品名称</th>
          <th>价格</th>
          <th>数量</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(product, index) in search" :key="index">
          <td>{{ product.name }}</td>
          <td>{{ product.price }}</td>
          <td><button @click="product.quantity--">-</button>{{ product.quantity }}<button @click="product.quantity++">+</button></td>
          <td>
            <button @click="del(index)">删除</button>
          </td>
        </tr>
      </tbody>
      
    </table>
    <p>您需要支付{{ _total }}</p>
    <button @click="allbuy">我全都要</button>
    <p v-show="showbuy">要全买?所有商品总价:{{total }}</p>
  </div>
  </div>
</template>

<script setup lang="ts">
import{ref,reactive,computed} from 'vue'
    let keyword = ref<string> ('')

    interface Data{
        name:string,
        price:number,
        quantity:number
    }

    let showbuy = ref<boolean>(false)

    const data = reactive<Data[]> ([
        { name: '商品1', price: 10, quantity: 5 },
        { name: '商品2', price: 20, quantity: 3 },
        { name: '商品3', price: 15, quantity: 2 }
    ])


    const total = computed(()=>{
        return data.reduce((prev:number,next:Data)=>{
            return prev + next.price * next.quantity; 
        },0)
    })

    const _total = computed(()=>{
        const searchResult = search.value; // 获取search计算属性的值
        return searchResult.reduce((prev:number,next:Data)=>{
            return prev + next.price * next.quantity; 
        },0)
    })

    const search = computed(()=>{
        const mysearch = data.filter((product:Data)=>{
            return product.name.includes(keyword.value)
        })
        return mysearch
    })

    const del = (index:number) =>{
        data.splice(index,1)
    }

    const allbuy = () =>{
        showbuy.value=!showbuy.value
    }
</script>

<style>
    .sou{
        color: red;
    }
</style>

3.购物车案例中用到的函数
(1)filter
在JavaScript中,filter()方法是数组对象的一个高阶函数,它用于筛选数组元素并返回一个新的数组,新数组只包含满足特定条件的元素。
filter.html

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Array.filter()</h1>

<p>使用通过测试的所有数组元素创建一个新数组。</p>

<p id="demo"></p>

<script>
var numbers = [45, 4, 9, 16, 25];
var over18 = numbers.filter(myFunction);

document.getElementById("demo").innerHTML = over18;

function myFunction(value, index) {
	console.log("值:",value,"索引:",index)
  return value > 18&index>0;
}
</script>

</body>
</html>

效果图如下:
在这里插入图片描述
以下是示例代码,展示了如何使用filter()方法:

let strings = ["hello", "", "world", "", ""];

let nonEmptyStrings = strings.filter((str) => str !== "");

console.log(nonEmptyStrings); // 输出 ["hello", "world"]

(2)reduce
在JavaScript中,reduce()方法是数组对象的一个高阶函数,它用于对数组中所有元素进行累积计算,并返回一个单一的值。
以下是示例代码,展示了如何使用reduce()方法:
accumulator: 累加器的初始值或上一次回调函数的返回值。
currentValue: 当前被处理的元素。

let strings = ["Hello", " ", "World", "!"];
let result = strings.reduce((accumulator, currentValue) => accumulator + currentValue);

console.log(result); // 输出 "Hello World!"

let numbers = [10, 5, 8, 20, 15];
let maxNumber = numbers.reduce((accumulator, currentValue) => Math.max(accumulator, currentValue));

console.log(maxNumber); // 输出 20

(3)splice
在JavaScript中,splice()方法用于向数组中插入、删除或替换元素,并返回被修改的数组。
splice()方法可以接受多个参数,具体取决于你想要进行的操作:

let fruits = ['apple', 'banana', 'orange', 'mango'];
fruits.splice(2, 1); // 从索引2开始,删除一个元素

console.log(fruits); // 输出:['apple', 'banana', 'mango']

let fruits = ['apple', 'banana', 'mango'];
fruits.splice(1, 0, 'cherry'); // 在索引1处插入'cherry'

console.log(fruits); // 输出:['apple', 'cherry', 'banana', 'mango']

fruits.splice(1, 0, ‘cherry’) 的意思是在 fruits 数组的索引 1 处插入一个新元素 ‘cherry’,并且不删除任何元素(因为第二个参数为 0)。此操作将会改变 fruits 数组,并在索引 1 处插入 ‘cherry’。

let fruits = ['apple', 'banana', 'mango'];
fruits.splice(0, 1, 'grape'); // 替换索引0处的元素为'grape'

console.log(fruits); // 输出:['grape', 'banana', 'mango']

第一个参数表示要进行修改的起始位置(索引),第二个参数表示要删除的元素数量,而后面的参数则是要插入到数组中的新元素。
在这种情况下,splice() 方法会从 fruits 数组的索引 0 处开始,删除 1 个元素,并将 ‘grape’ 插入到此位置。这样就实现了将原来索引 0 处的元素替换为 ‘grape’ 的操作。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值