Blog>
Snippets

Dynamic Props Binding

Show dynamically binding props to values using `v-bind` with an object syntax in Vue.js 3.
<template>
  <div>
    <!-- Dynamic props binding using v-bind with an object syntax -->
    <button v-bind="buttonProps">Click Me!</button>
  </div>
</template>
This is the HTML part of the Vue component. It uses v-bind with an object to dynamically bind multiple attributes to a <button> element. The 'buttonProps' is an object that will contain the attributes as key-value pairs.
<script>
import { ref } from 'vue';

export default {
  setup() {
    // Define a reactive object that contains properties for the button
    const buttonProps = ref({
      type: 'submit',
      class: 'btn-primary',
      disabled: false
    });

    // You can dynamically update buttonProps here
    // For example, disable the button
    // buttonProps.value.disabled = true;

    return {
      buttonProps
    };
  }
};
</script>
This is the JavaScript part of the Vue component with the Composition API. It creates a reactive object 'buttonProps' containing the props we want to bind to the button element. This object can be dynamically updated, and changes will be automatically reflected in the template.
<style>
.btn-primary {
  background-color: #007bff;
  color: white;
  border: none;
  padding: 10px 15px;
  border-radius: 5px;
  cursor: pointer;
}

.btn-primary:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}
</style>
This is the CSS styling for the button. It defines the primary button style and the style to be applied when the button is disabled.