How to use shorthand : in Vue
Using shorthand colon syntax in Vue provides a concise alternative to v-bind directive for attribute binding with cleaner and more readable template code. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented shorthand syntax in thousands of Vue components to improve code readability and developer productivity. From my expertise, the most effective approach is using colon shorthand consistently for all attribute binding to maintain clean templates. This method reduces verbose syntax while maintaining the same functionality as the full v-bind directive.
Use :
as shorthand for v-bind:
to bind data to HTML attributes concisely.
<template>
<div>
<!-- Full v-bind syntax -->
<img v-bind:src="imageUrl" v-bind:alt="imageAlt">
<!-- Shorthand colon syntax (preferred) -->
<img :src="imageUrl" :alt="imageAlt">
<!-- Class and style binding -->
<div :class="dynamicClass" :style="dynamicStyle">
Styled content
</div>
<!-- Props binding -->
<user-card
:user="currentUser"
:show-avatar="true"
:loading="isLoading">
</user-card>
<!-- Multiple attributes -->
<button
:disabled="isSubmitting"
:class="buttonClass"
:title="buttonTooltip"
@click="handleSubmit">
{{ buttonText }}
</button>
</div>
</template>
<script setup>
import { ref, computed } from 'vue'
const imageUrl = ref('/images/profile.jpg')
const imageAlt = ref('User profile')
const currentUser = ref({ name: 'John Doe', email: '[email protected]' })
const isLoading = ref(false)
const isSubmitting = ref(false)
const dynamicClass = computed(() => ({
'active': !isLoading.value,
'loading': isLoading.value
}))
const dynamicStyle = computed(() => ({
opacity: isLoading.value ? 0.5 : 1
}))
const buttonClass = computed(() =>
isSubmitting.value ? 'btn btn-secondary' : 'btn btn-primary'
)
const buttonText = computed(() =>
isSubmitting.value ? 'Submitting...' : 'Submit'
)
const buttonTooltip = ref('Click to submit form')
const handleSubmit = () => {
isSubmitting.value = true
}
</script>
The colon :
is shorthand for v-bind:
and works identically for all attribute binding scenarios. Use it consistently throughout your templates for cleaner code. Both syntaxes enable reactive data binding to HTML attributes with the same functionality and performance.
Best Practice Note:
This is the same shorthand syntax we use in CoreUI Vue components for clean and maintainable templates. Always use the colon shorthand consistently across your project to maintain code style and improve readability for your development team.