我有一个简单的代码:
<div id="app">
<div class="xyz" :class="{ selectedRadio:radio_first }">
<input type="radio" name="example" @change="radio_first = true;radio_second = false">
</div>
<div class="abc" :class="{ selectedRadio:radio_second }">
<input type="radio" name="example" @change="radio_second = true;radio_first = false">
</div>
</div>
然后:
new Vue({
el:"#app",
data:{
radio_first:false,
radio_second:false
}
});
CSS:
.xyz{
display:inline;
padding:20px;
border:1px solid grey;
margin-right:60px;
}
.abc{
border:1px solid grey;
display:inline;
padding:20px;
}
.selectedRadio{
background: lightgreen;
}
因此,如果我选中第一个单选按钮,我只想向其父 div 添加一个新类。如果我检查第二个 radio ,我需要向其父 div 添加一个类,并将第一个添加的类删除到第一个 radio 父 div。 我希望你们明白我想要什么。到目前为止我已经尝试过了。它正在工作,但是如果我有很多单选按钮怎么办?vue js 中有没有更好的方法来解决这个问题。 这是代码笔链接:https://codepen.io/kohalirakesh/pen/KoPMEZ 谢谢。
最佳答案
像这样吗? Example on Codesandbox
您基本上想使用 :class
,例如:
<div class="parent" :class="{'green': radio}">
<input type="radio" v-model="radio" :value="true"/> True
</div>
<div class="parent" :class="{'red': !radio}">
<input type="radio" v-model="radio" :value="false"/> False
</div>
您可以在 Vue 官方文档中阅读更多相关信息:
关于javascript - 如何在vuejs中的更改单选按钮上从父div添加/删除类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49158512/