gpt4 book ai didi

javascript - 如何在 vue.js 中单击时切换类?

转载 作者:搜寻专家 更新时间:2023-10-30 22:59:55 25 4
gpt4 key购买 nike

我有一个组件可以为用户显示多个选项。用户应该能够点击他喜欢的选项,然后发送表单。

为了给用户某种反馈,我想切换一个类 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com