[Vue] Vue 3.2 <style> v-bind
<style> v-bind
is a new feature in Vue 3.2 that might remind you of v-bind:style
, which is a classic Vue.js technique for binding some reactive value to the styles of an element:
<script setup lang="ts">
import { ref } from 'vue'
const borderStyle = ref('2px solid black')
</script>
<template>
<input v-bind:style="{ border: borderStyle }" />
</template>
<style> v-bind
serves the same purpose, but instead of binding the reactive value to the style
attribute in the <template>
, we are binding it to a CSS property in the <style>
tag
<script setup lang="ts">
import { ref } from 'vue'
const borderStyle = ref('2px solid black')
</script>
<template>
<input />
</template>
<style scoped>
.textbox {
border: v-bind(borderStyle)
}
</style>
And we have to add the class
attribute on the element:
<template>
<input class="textbox" />
</template>
So between <style> v-bind
and v-bind:style
, which one should you use?
It’s mostly a style preference. If you want your style bindings to be separated from the other bindings in the <template>
, you can use <style> v-bind
.
But what’s more important is consistency. If you’re using <style> v-bind
in a component, you should use only that within the same component. Having two different ways of binding the styles in the same component makes the code harder to make sense of.
If you want to learn more about <style> v-bind
, you can check out the documentation for that.