使用v-for获取元素的唯一ID,并访问CSS中的特定ID



我正在尝试用一个唯一的ID来标识v-for指令的每个元素,这样我就可以用该ID访问HTML对象并更改其CSS。目前,这是我的Vue HTML。

<!DOCTYPE html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<script type="text/javascript" src="assets/js/vue@2.6.12/dist/vue.js"></script>
<title>remoteProto</title>     
<style type="text/css">
html,
.switch {
white-space: nowrap;
display: inline-block;
padding: 30px;
background-color: rgb(255, 223, 223);
background-repeat: no-repeat;
background-size: 100%;
position: relative;
top: 24px;
right: 194px;
transform: rotate(0deg);
}
.switch.closed {
background-image: url(assets/image/switch-closed.svg);
background-position: 0px 0px;
}
.switch.opened {
background-image: url(assets/image/switch-opened.svg);
background-position: 0px -7.5px;
}
</style>
</head>
<div id="app">
<fieldset style="background-color: rgb(181, 207, 209);">
<h1>simTest server</h1>
<hr>
<div class="circuitplan">
<div v-for="(val, key) in switchObj" v-bind:key="key">
<div>{{ key }}
<span class="switch" v-bind:class="{ closed: val==='closed', opened: val==='opened' }" @click="onSwitchClick(key)" ></span>
</div>
</div>
</div>
</fieldset>
</div>
<script>
const app = new Vue({
el: '#app',
data () {
return {
ws: null,
idCount: 1,
url: 'ws://localhost:3000',
switchObj: {
/*'K1': 'opened',
'K2': 'opened',
'K3': 'opened'
*/
},  
sentObj: {},
}
},
})

</script>
</html>

如何更改此特定ID的CSS?让我们说"键";命名如下:";K1〃"K2"K3"。。。类是";开关";。我知道这是不对的,但为了说明我的意思,我想有这样的东西:

开关.K1{K2以外的其他位置}转换K2{…}

此外,开关被绑定为关闭和打开,请参阅CSS。我想我的HTML语法揭示了我是一个傻瓜。不管怎样,我希望你们能帮助我,谢谢!

您有两个选择:

1-为每个元素定义一个唯一的,然后定义其样式,如:

K1{
...
}
K2{
...
}
...
Kn{
...
}

模板(key表示KEY1KEY2…(:

<div v-for="(val, key,index) in switchObj" v-bind:id="key">

2-定义包含每个元素样式的数据属性,并使用密钥将其绑定到元素:

url: 'ws://localhost:3000',
style:{
K1:{
color:'red'
},
K2:{
color:'geen'
}
}

在模板中使用内联样式绑定:

<div v-for="(val, key,index) in switchObj" v-bind:style="style[key]">

最新更新