K
K
kimqarkimqarkimqar2021-08-05 12:32:31
Vue.js
kimqarkimqarkimqar, 2021-08-05 12:32:31

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>

When clicking on the input in the second parent or in the first parent on the block with the buy-voucher-choose class, the buy-voucher_amount_selected class should be added to the active element, how to do this?
I did it in jquery, but I want to translate it into vue, it doesn't work
$('#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

2 answer(s)
0
0xD34F, 2021-08-05
@kimqarkimqarkimqar

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'">

A
Alex, 2021-08-05
@Kozack Vue.js

You don't need any class there at all. In your case it is enough to use :focus-within

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question