目录
一、问题
二、解决方法
三、总结
tiips:如嫌繁琐,直接移步总结即可!
一、问题
computed可以依据其他变量动态计算出值,但是v-for渲染html时,需要根据html中 传入的不同变量,来分别做处理或者利用 html中的值该怎么办呢?
二、解决方法
template中使用 computed计算属性时,添加传参
computed函数中返回 一个函数,函数的参数就是使用计算属性时添加的参数
1.template中传参:getPieceStyle 计算属性(params1,params2)
<template><ul class="over-turn"><li class="bg-color sp-piece":style="getPieceStyle(index,item)"v-for="(item, index) in [8,9,10]":key="index">{{item}}</li></ul></template>const getPieceStyle = computed(() => {return function (index,item) {console.log('computed function',index,item)//拿到html中传入的 参数 index和item了//逻辑处理return return {background:item*10 >=curSpo2Beat.value?'#777':'red'};};// return (index,item)=>{// console.log("computed function",index,item)// }});
2. setup中传参: compute属性.value(params1,params2) (不建议)
setup(props){const getPieceStyle = computed(() => {return (index,item)=>{console.log("computed function",index,item)return {background:index>3?'red':'green'}}});console.log("computed function result",getPieceStyle.value(5,'test'))
}
三、总结
1.computed传参的方式:computed属性返回值一个 函数即可。此时computed的返回值是一个函数。
注:setup中 计算属性.value才是一个函数; compute属性.value(params1,params2)
template中vue已经解构出计算属性了,所以可以直接使用 计算属性(params1,params2)
2.计算属性一般用于 html渲染,所以不建议 在setup中直接使用
/*
希望对你有帮助!
如有错误,欢迎指正,非常感谢!
*/