Vue学习记录之四(computed的用法)

news/2024/9/18 23:58:07 标签: vue.js, 学习, 前端

computed 属性用于创建计算属性。计算属性是基于现有响应式数据派生出的值,它会自动缓存,只有当依赖的响应式数据发生变化时,计算属性才会重新计算,这样可以提高性能和避免不必要的重复计算。

书写有两种方法: 1、选项式写法,2、函数式写法

<template>
    <div>: <input v-model="firstName" type="text" >
    </div>
    <div>: <input v-model="lastName" type="text" >
    </div>
    <div>: <input v-model="name" type="text" >
    </div>
    <button @click="change">修改名字</button>
</template>
<script setup lang='ts'>
import { ref,reactive,computed } from 'vue'
let firstName = ref('张')
let lastName = ref('三')
//1.选项式写法支持一个对象传入get函数以及set函数自定义操作
/*
let name = computed<string>({
  get() {
    return firstName.value + "-" + lastName.value 
  },
  set(newVal){
    console.log(newVal.split("-"));
    [firstName.value,lastName.value] = newVal.split("-")
  }
})
*/
//2.函数式写法 只能支持一个getter函数不允许修改值的
let name = computed(()=>firstName.value + '-' + lastName.value)

const change = () =>{
  name.value = "赵-四"    //如果使用第二种用法,这里将会报错。
}
</script>

实战购物车,使用原始的方法实现

<template>
    <div style="margin:auto">
      <table border width="600" cellpadding="0" cellspacing="0" center>
        <thead>
          <tr><th>名称</th><th>单价</th><th>数量</th><th>总价</th><th>操作</th></tr>
        </thead>
        <tbody><tr v-for="(item,index) in data">
              <td>{{item.name}}</td>
              <td>{{item.price}}</td>
              <td><button @click="item.num > 1 ? (item.num--,total()) : null">-</button>
              {{item.num}}
              <button @click="item.num > 99 ? null : (item.num++,total())">+</button>
              </td>
              <td>{{item.num * item.price}}</td>
              <td><button @click="del(index)">删除</button></td>
            </tr></tbody>
        <tfoot><tr><td colspan="5">{{$total}}</td></tr></tfoot>
      </table>
    </div>
</template>
<script setup lang='ts'>
import { ref,reactive } from 'vue'
let $total = ref<number>(0)
interface Data{
  name: string,
  price: number,
  num: number
}
let data = reactive<Data[]>([
  {
    name: "张1",
    price: 50,
    num: 1
  },
  {
    name: "张2",
    price: 100,
    num: 2
  },
  {
    name: "张3",
    price: 150,
    num: 3
  },
  {
    name: "张4",
    price: 200,
    num: 4
  },
])
let total = () => {
  $total.value = data.reduce((prev:number,next:Data)=>{
    return prev + next.num * next.price
  },0)
}
total()
const del=(index:number)=>{
  data.splice(index,1)  //splice() 方法用于添加或删除数组中的元素
  total()
}
</script>

购物车加入computer函数带来的便捷

<template>
    <div style="margin:auto">
      <table border width="600" cellpadding="0" cellspacing="0" center>
        <thead>
          <tr><th>名称</th><th>单价</th><th>数量</th><th>总价</th><th>操作</th></tr>
        </thead>
        <tbody><tr v-for="(item,index) in data">
              <td>{{item.name}}</td>
              <td>{{item.price}}</td>
              <td><button @click="item.num > 1 ? item.num-- : null">-</button>
              {{item.num}}
              <button @click="item.num > 99 ? null : item.num++">+</button>
              </td>
              <td>{{item.num * item.price}}</td>
              <td><button @click="del(index)">删除</button></td>
            </tr></tbody>
        <tfoot><tr><td colspan="5">{{ total }}</td></tr></tfoot>
      </table>
    </div>
</template>
<script setup lang='ts'>
import { ref,reactive, computed } from 'vue'
interface Data{
  name: string,
  price: number,
  num: number
}
let data = reactive<Data[]>([
  {
    name: "张1",
    price: 50,
    num: 1
  },
  {
    name: "张2",
    price: 100,
    num: 2
  },
  {
    name: "张3",
    price: 150,
    num: 3
  },
  {
    name: "张4",
    price: 200,
    num: 4
  },
])
const total = computed(() => {
  return data.reduce((prev:number,next:Data)=>{
    return prev + next.num * next.price
  },0)
})

const del=(index:number)=>{
  data.splice(index,1)  //splice() 方法用于添加或删除数组中的元素
}
</script>

购物车添加搜索功能

<template>
    <input v-model="keyword" placeholder="搜索" type="text">
    <div style="margin:auto">
      <table border width="600" cellpadding="0" cellspacing="0" center>
        <thead>
          <tr><th>名称</th><th>单价</th><th>数量</th><th>总价</th><th>操作</th></tr>
        </thead>
        <tbody><tr v-for="(item,index) in searchData">
              <td>{{item.name}}</td>
              <td>{{item.price}}</td>
              <td><button @click="item.num > 1 ? item.num-- : null">-</button>
              {{item.num}}
              <button @click="item.num > 99 ? null : item.num++">+</button>
              </td>
              <td>{{item.num * item.price}}</td>
              <td><button @click="del(index)">删除</button></td>
            </tr></tbody>
        <tfoot><tr><td colspan="5">{{ total }}</td></tr></tfoot>
      </table>
    </div>
</template>
<script setup lang='ts'>
import { ref,reactive, computed } from 'vue'
let keyword = ref<string>("")
interface Data{
  name: string,
  price: number,
  num: number
}
let data = reactive<Data[]>([
  {
    name: "张1",
    price: 50,
    num: 1
  },
  {
    name: "张2",
    price: 100,
    num: 2
  },
  {
    name: "张3",
    price: 150,
    num: 3
  },
  {
    name: "张4",
    price: 200,
    num: 4
  },
])
const total = computed(() => {
  return searchData.value.reduce((prev:number,next:Data)=>{
    return prev + next.num * next.price
  },0)
})
const searchData = computed(()=>{
  return data.filter((item:Data)=>{
    return item.name.includes(keyword.value)
  })
})
const del=(index:number)=>{
  data.splice(index,1)  //splice() 方法用于添加或删除数组中的元素
}
</script>

知识点:
1、在 TypeScript 中,type 和 interface 都可以用来定义对象的形状。
扩展性: interface 支持接口继承,可以通过 extends 关键字继承其他接口。接口可以多次声明并合并(声明合并)。实现: 类可以实现一个或多个接口,确保类符合接口的结构。
组合性: type 支持更多的类型组合操作,如联合类型、交叉类型等。它可以用于定义复杂的类型别名。
不可扩展: type 不能进行声明合并,定义后不能再扩展或重新声明。

2、reduce函数的使用
reduce()是JavaScript的数组方法之一,它接受一个回调函数作为其参数,并返回一个单一的值。该方法可用于
对数组的所有项进行迭代,并将它们合并为一个最终值。reduce()方法在处理Vue数组中的大量数据时非常有
用。

array.reduce(
callback(accumulator, currentValue, currentIndex, array),
initialValue
);
callback: 这是一个回调函数,作用是将数组中的每一个元素逐个处理。回调函数接收四个参数:

accumulator: 累加器,保存上一次调用回调函数时的返回值(即中间结果)。
currentValue: 数组中当前处理的元素。
currentIndex: 当前元素的索引(可选)。
array: 当前被遍历的数组(可选)。
initialValue: 可选参数,表示累加器的初始值。如果没有提供,reduce() 会将数组的第一个元素作为初始值,并从第二个元素开始迭代。

//1、计算数组中所有元素的总和 
const numbers = [1, 2, 3, 4, 5]; 
const sum = numbers.reduce(
(total, current) => total + current, 
0); 
console.log(sum); //输出:15
//2、求数组中的最大值
const numbers = [10, 5, 7, 20, 25]; 
const max = numbers.reduce((previous, current) => previous > current ? previous : current); 
console.log(max); //输出:25

3、filter 方法用于创建一个新数组,其中包含所有通过指定函数测试的元素。filter 不会改变原数组,而是返回一个新的数组。

let newArray = array.filter(callback(element[, index[, array]])[, thisArg])
/*
callback: 用来测试数组每个元素的函数,返回 true 表示保留该元素,返回 false 表示丢弃该元素。该函数接收三个参数:
element: 当前处理的元素。
index (可选): 当前处理元素的索引。
array (可选): 调用 filter 的原数组。
thisArg (可选): 执行 callback 时,用作 this 的值。
*/

实例

//实例1
const numbers = [5, 12, 8, 130, 44];
const filteredNumbers = numbers.filter(function(number) {
  return number > 10;
});
console.log(filteredNumbers);
// 输出: [12, 130, 44]
//实例2 使用箭头函数
const numbers = [5, 12, 8, 130, 44];
const filteredNumbers = numbers.filter(number => number > 10);
console.log(filteredNumbers);
// 输出: [12, 130, 44]
//实例3
const words = ["spray", "limit", "elite", "exuberant", "destruction", "present"];
const longWords = words.filter(word => word.length > 6);
console.log(longWords);
// 输出: ["exuberant", "destruction", "present"]

//实例4
const numbers = [5, 12, 8, 130, 44];
const filteredNumbers = numbers.filter((number, index) => index % 2 === 0);
console.log(filteredNumbers);
// 输出: [5, 8, 44]

http://www.niftyadmin.cn/n/5664735.html

相关文章

文件操作

1.文件的打开和关闭 文件在读写之前应该先打开文件&#xff0c;在使用结束之后应该关闭文件。 在编写程序的时候&#xff0c;在打开文件的同时&#xff0c;都会返回一个FILE*的指针变量指向该文件&#xff0c;也相当于建立了指针和文件的关系。ANSI C规定使用fopen函数来打开文…

【python】30、矩阵加法 tensor.sum

文章目录 一、tensor.sum 一、tensor.sum 为了更好地理解 torch.sum 函数中 dim 参数的作用&#xff0c;我们可以将三维张量的求和过程分解&#xff0c;并通过具体的例子来说明不同 dim 参数的效果。### 三维张量的结构假设我们有一个 3x2x2 的张量&#xff0c;如下所示&#…

【JavaEE初阶】多线程6(线程池\定时器)

欢迎关注个人主页&#xff1a;逸狼 创造不易&#xff0c;可以点点赞吗~ 如有错误&#xff0c;欢迎指出~ 目录 实例3:线程池 参数解释 核心线程数, 最大线程数 允许空闲的最大时间 ,时间单位 任务队列(阻塞队列) 线程工厂>工厂设计模式 拒绝策略 使用举例 模拟实现一个线…

windows使用tcpdump.exe工具进行抓包教程

windows主机安装一些抓包工具可能有些不方便&#xff0c;这里有一个tcpdump.exe工具直接免安装&#xff0c;可以直接使用进行抓包。&#xff08;工具下载见 附件&#xff09; tcpdump.exe使用教程 如下&#xff1a; 1&#xff1a;tcpdump -D 可查看网络适配器(注意前面的编号)…

OpenHarmony(鸿蒙南向开发)——轻量和小型系统三方库移植指南(一)

往期知识点记录&#xff1a; 鸿蒙&#xff08;HarmonyOS&#xff09;应用层开发&#xff08;北向&#xff09;知识点汇总 鸿蒙&#xff08;OpenHarmony&#xff09;南向开发保姆级知识点汇总~ OpenHarmony&#xff08;鸿蒙南向开发&#xff09;——轻量系统芯片移植指南(一) Op…

Web植物管理系统-下位机部分

本节主要展示上位机部分&#xff0c;采用BSP编程&#xff0c;不附带BSP中各个头文件的说明&#xff0c;仅仅是对main逻辑进行解释 main.c 上下位机通信 通过串口通信&#xff0c;有两位数据验证头&#xff08;verify数组中保存对应的数据头 0xAA55) 通信格式 上位发送11字节…

Python那些关于字符串的操作

Python那些关于字符串的操作 1 前言2 字符串的处理操作.2.1分割字符串2.2拼接字符串2.3正则表达式2.4enumerate2.5字符串中的大小写转化2.6 对齐加数 总结 1 前言 python关于字符串的操作很多&#xff0c;而正则化直接是打开新世界的大门。同一种说法&#xff0c;使用不同语言…

【Ubuntu】Ubuntu双网卡配置 实现内外网互不影响同时可用

【Ubuntu】Ubuntu双网卡配置 实现内外网互不影响同时可用 建议前提配置用到的命令参考文献&#xff1a; 建议 本文仅作个人记录&#xff0c;请勿完全照搬&#xff0c;建议直接看此视频&#xff0c;按作者的步骤进行配置 linux配置内外网&#xff08;ubuntu举例&#xff09;&am…