欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 建筑 > Vue学习记录之四(computed的用法)

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

2024/10/25 10:29:41 来源:https://blog.csdn.net/LvManBa/article/details/142317657  浏览:    关键词:Vue学习记录之四(computed的用法)

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]

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com