JavaScript Q&A Logo
JavaScript Q&A Part of the Q&A Network

How do directives work in Vue.js?

Asked on Sep 27, 2024

Answer

In Vue.js, directives are special tokens in the markup that tell the library to do something to a DOM element. They are prefixed with "v-" and provide special reactive behavior to the DOM.
<!-- BEGIN COPY / PASTE -->
        <div id="app">
            <p v-if="isVisible">This text is conditionally rendered.</p>
        </div>

        <script>
            const app = new Vue({
                el: '#app',
                data: {
                    isVisible: true
                }
            });
        </script>
        <!-- END COPY / PASTE -->
Additional Comment:
  • The "v-if" directive conditionally renders the paragraph based on the "isVisible" data property.
  • Vue.js directives are used to bind data to the DOM and control DOM behavior.
  • Common directives include "v-if", "v-for", "v-bind", and "v-on".
  • Directives can have arguments and modifiers to extend their behavior.
✅ Answered with JavaScript best practices.
← Back to All Questions