Today we’ll have a look at how we can bind CSS styles to elements conditionally (dynamically) in Vue 3. We’ll take an example of an input field where we’d set its border color to red and then to black. We’ll toggle between these two options using a button.
First, we must import the ref from vue at the top of our setup script.
import { ref } from 'vue'
Code language: JavaScript (javascript)
Next, we create a reactive state named showRedBorder and set its value to false using the ref function. This state will be used to track whether the border should be red or not.
const showRedBorder = ref(false)
Code language: JavaScript (javascript)
Now we will create a function called toggleShowBorder that will toggle the value of showRedBorder between true and false every time it’s called.
const toggleShowBorder = () => {
showRedBorder.value = !showRedBorder.value
}
Code language: JavaScript (javascript)
In the template section, we will create an input element and use the v-bind:style directive to bind the style attribute to it. We will use a ternary operator to check the value of showRedBorder and set the border style accordingly. If showRedBorder is true, the border style will be 1px solid red, otherwise, it will be 1px solid #000.
<template>
<input
type="text"
v-bind:style="showRedBorder ?
'border: 1px solid red;' :
'border: 1px solid #000;'"
/>
Code language: HTML, XML (xml)
Finally, we will create a button element and use the @click event to call the toggleShowBorder function. This button will be used to toggle the border style of the input element.
<button @click="toggleShowBorder">
Toggle border
</button>
</template>
Code language: HTML, XML (xml)
Now, when you run the app, you should be able to toggle the border style of the input element between red and black by clicking the toggle border button.
Here’s the complete code:
<script setup>
import { ref } from 'vue'
const showRedBorder = ref(false)
const toggleShowBorder = () => {
showRedBorder.value = !showRedBorder.value
}
</script>
<template>
<input
type="text"
v-bind:style="showRedBorder ?
'border: 1px solid red;' :
'border: 1px solid #000;'"
/>
<button @click="toggleShowBorder">
Toggle border
</button>
</template>
Code language: HTML, XML (xml)