<template>
<view style="">
<button @tap="changeColor">改变颜色</button>
<view v-for="(item, index) in list" :style="{
backgroundColor: typeColors[item.type],
padding: '30rpx',
marginBottom: '24rpx',
}">
---- {{index}} ----
</view>
</view>
</template>
<script>
export default {
data() {
return {
typeColors: {
'0':'pink',
'1':'red',
'2':'blue'
},
list: [{
type:'0',
id:'1'
},{
type:'1',
id:'2'
},{
type:'2',
id:'3'
},{
type:'2',
id:'4'
},{
type:'1',
id:'5'
},{
type:'1',
id:'6'
}],
}
},
methods: {
changeColor() {
this.typeColors['0'] = 'lightcyan'
this.typeColors['1'] = 'darkblue'
this.typeColors['2'] = 'violet'
}
}
}
</script>
3 个回复
爱豆豆 - 办法总比困难多
你复制运行一下 是这种效果吗?
爱豆豆 - 办法总比困难多
是这样的效果吗?
r***@126.com (作者)
类似这个意思。但是因为computed是响应式驱动的,不是点击事件驱动的,所以还有点不一样。比如说我用v-for渲染了一个列表,然后当用户点击其中某项时,改变被点到的项的颜色。那我可能就会给v-for的元素加一个 :style="computedFn(index)" 这样的动态样式。这个computedFn就得接收一个入参了。我实际试下来在微信小程序里不能这么写。
2023-06-14 16:47
爱豆豆
回复 r***@126.com: 那你h5是怎么写的呢?
2023-06-14 17:08
r***@126.com (作者)
回复 爱豆豆: 比如说我有个列表<view :style="computedFn(index)" v-for="(item,index) in list">这样子。然后computed:{
computedFn(){
let that = this;
return function(index){
return some style;
}
}
}
这样我就可以根据列表里的不同index类指定每个view可以用不同的样式了。而且整个过程是响应式自动的,style依赖的数据发生变化,style就会变化,不用手动指定刷新数据。
2023-06-16 11:44
r***@126.com (作者)
回复 爱豆豆: 但是这个方法在微信小程序里行不通,在微信小程序里computed的函数似乎不能是高阶函数。
2023-06-16 11:45
爱豆豆
回复 r***@126.com: 是的 我测了一下 提示我 :style 不支持 computedFn(index) 语法
2023-06-16 12:07
r***@126.com (作者)
回复 爱豆豆: 有啥解决办法吗?我就是想让同一个v-for生成的view可以根据不同的状态有不同的style或者class也行
2023-06-16 15:18
爱豆豆
回复 r***@126.com: 有 有状态控制的情况下久更简单了
2023-06-16 15:37
爱豆豆 - 办法总比困难多
<template>
<view style="">
<button @tap="changeColor">改变颜色</button>
<view v-for="(item, index) in list" :style="{
backgroundColor: typeColors[item.type],
padding: '30rpx',
marginBottom: '24rpx',
}">
---- {{index}} ----
</view>
</view>
</template>
<script>
export default {
data() {
return {
typeColors: {
'0':'pink',
'1':'red',
'2':'blue'
},
list: [{
type:'0',
id:'1'
},{
type:'1',
id:'2'
},{
type:'2',
id:'3'
},{
type:'2',
id:'4'
},{
type:'1',
id:'5'
},{
type:'1',
id:'6'
}],
}
},
methods: {
changeColor() {
this.typeColors['0'] = 'lightcyan'
this.typeColors['1'] = 'darkblue'
this.typeColors['2'] = 'violet'
}
}
}
</script>