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

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

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

ts 复制代码
<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>

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

ts 复制代码
<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函数带来的便捷

ts 复制代码
<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>

购物车添加搜索功能

ts 复制代码
<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() 会将数组的第一个元素作为初始值,并从第二个元素开始迭代。

ts 复制代码
//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 不会改变原数组,而是返回一个新的数组。

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

实例

ts 复制代码
//实例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]
相关推荐
无心使然云中漫步8 分钟前
GIS OGC之WMTS地图服务,通过Capabilities XML描述文档,获取matrixIds,origin,计算resolutions
前端·javascript
Bug缔造者14 分钟前
Element-ui el-table 全局表格排序
前端·javascript·vue.js
铁匠匠匠15 分钟前
从零开始学数据结构系列之第六章《排序简介》
c语言·数据结构·经验分享·笔记·学习·开源·课程设计
xnian_1 小时前
解决ruoyi-vue-pro-master框架引入报错,启动报错问题
前端·javascript·vue.js
罗政1 小时前
[附源码]超简洁个人博客网站搭建+SpringBoot+Vue前后端分离
vue.js·spring boot·后端
麒麟而非淇淋2 小时前
AJAX 入门 day1
前端·javascript·ajax
架构文摘JGWZ2 小时前
Java 23 的12 个新特性!!
java·开发语言·学习
2401_858120532 小时前
深入理解MATLAB中的事件处理机制
前端·javascript·matlab
小齿轮lsl2 小时前
PFC理论基础与Matlab仿真模型学习笔记(1)--PFC电路概述
笔记·学习·matlab
阿树梢2 小时前
【Vue】VueRouter路由
前端·javascript·vue.js