Home > database >  How to utilize a callback in a conditional in VueJS
How to utilize a callback in a conditional in VueJS

Time:07-26

I need to change the focus styling in vueJS i have a call that find a focused element but I simply cant use it straight up in conditional rendering so I used a callback but I cant get the callback to work in the in line styling.

<template>
   <button
            ...
            :style="this.isThisElementActive() ? {'border':'solid 2px blue'} : ''"
            ref="shipToStoreZipCodeButton"
          >
            {{ locationName }}
          </button>
</template>


export default {
...
methods:{
...  isThisElementActive(){
      console.log(document.activeElement,this.$refs.shipToStoreZipCodeButton)
      return document.activeElement === this.$refs.shipToStoreZipCodeButton
    },
}

CodePudding user response:

You could achieve that by using the :focus pseudo class :

<template>
   <button   >
            {{ locationName }}
    </button>
</template>
<style>
.my-btn:focus{
  border: solid 2px blue
}
</style>

CodePudding user response:

In the template, you shouldn't use this

<template>
<button
        ...
    :style="isThisElementActive() ? {'border':'solid 2px blue'} : ''"
            ref="shipToStoreZipCodeButton"
          >
            {{ locationName }}
          </button>
 </template>

As this may cause unexpected bugs in runtime.

Question referance. Why sometimes 'this' works and sometimes doesn't in Vue template?

Also, it would be better to use computed instead, as isThisElementActive function doesn't take any parameter.

  • Related