作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我有一个组件可以为用户显示多个选项。用户应该能够点击他喜欢的选项,然后发送表单。
为了给用户某种反馈,我想切换一个类 v-on:click
。如何在我的 selectObjectType()
函数中为单击的 object.type
设置 object.selected = true
?
Vue.component('obj', {
props: ['name'],
template: '<div>{{ name }}</div>'
})
new Vue({
el: '#app',
data: {
message: 'Please select:',
objectTypes: [
{ type: 'Cat', selected: false },
{ type: 'Dog', selected: false },
{ type: 'Fish', selected: false },
{ type: 'Bear', selected: false },
],
},
methods: {
selectObjectType: function (object) {
console.log('Selected:', object.type)
// how can I change set object.selected = true for the clicked object.type?
}
}
})
.col {
height: 200px;
width: 20%;
cursor: pointer !important;
margin-right: 2.5%;
margin-left: 2.5%;
border-radius: 3px;
border: 1px solid lightgray;
padding: 20px;
box-sizing: border-box;
float: left;
}
.col:hover {
border-color: #000;
}
.col.selected {
border-color: green;
}
<script src="https://unpkg.com/vue"></script>
<div id="app">
<p>{{ message }}</p>
<obj
class="col"
v-for="object in objectTypes"
@click.native="selectObjectType(object)"
:key="object.id"
:name="object.type"
:class="{ 'selected': object.selected}"
>
</obj>
</div>
最佳答案
Vue.component('obj', {
props: ['name'],
template: '<div>{{ name }}</div>'
})
new Vue({
el: '#app',
data: {
message: 'Please select:',
objectTypes: [
{ type: 'Cat', selected: false },
{ type: 'Dog', selected: false },
{ type: 'Fish', selected: false },
{ type: 'Bear', selected: false },
],
},
methods: {
selectObjectType: function (object) {
object.selected = !object.selected;
console.log('Selected:', object.type)
}
}
})
.col {
height: 200px;
width: 20%;
cursor: pointer !important;
margin-right: 2.5%;
margin-left: 2.5%;
border-radius: 3px;
border: 1px solid lightgray;
padding: 20px;
box-sizing: border-box;
float: left;
}
.col:hover {
border-color: #000;
}
.col.selected {
border-color: green;
}
<script src="https://unpkg.com/vue"></script>
<div id="app">
<p>{{ message }}</p>
<obj
class="col"
v-for="object in objectTypes"
@click.native="selectObjectType(object)"
:key="object.id"
:name="object.type"
:class="object.selected ? 'selected' : ''"
>
</obj>
</div>
关于javascript - 如何在 vue.js 中单击时切换类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44796766/
我是一名优秀的程序员,十分优秀!