Answer the question
In order to leave comments, you need to log in
VueJS how to add class to active element in different parents?
There is a layout:
<div class="buy-voucher__amounts">
<div class="buy-voucher-choose buy-voucher__amount" v-for="(item,key) in vouchers" @click="changeVoucher(item.id)"><span class="buy-voucher__amount-text">£{{item.value}}</span></div>
</div>
<div class="buy-voucher__amounts">
<input class="buy-voucher__custom-input" id="value-custom__voucher" @click="changeVoucherCustom" v-on:input="changeVoucherCustom" v-model="CustomVoucherCount">
</div>
$('#value-custom__voucher').click( function () {
$('.buy-voucher__amount_selected').removeClass('buy-voucher__amount_selected');
$(this).addClass('buy-voucher__amount_selected');
})
$('.buy-voucher-choose').click( function () {
$('.buy-voucher__amount_selected').removeClass('buy-voucher__amount_selected');
$(this).addClass('buy-voucher__amount_selected');
})
Answer the question
In order to leave comments, you need to log in
You can make a directive:
function onClick({ currentTarget: t }) {
const className = t.dataset.activeClass;
document.querySelector(`.${className}`)?.classList.remove(className);
t.classList.add(className);
}
Vue.directive('active-class', {
bind(el, binding) {
el.dataset.activeClass = binding.value;
el.addEventListener('click', onClick);
},
update(el, binding) {
el.dataset.activeClass = binding.value;
},
unbind(el) {
delete el.dataset.activeClass;
el.removeEventListener('click', onClick);
},
});
<div v-active-class="'buy-voucher__amount_selected'">
<input v-active-class="'buy-voucher__amount_selected'">
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question