Chisom Kanu
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    1
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Directives In Vuejs ## Introduction [Vue.js](https://vuejs.org/) is a [javascript framework ](https://www.tutorialspoint.com/what-is-a-javascript-framework#:~:text=What%20Is%20a%20JavaScript%20Framework%3F%20JS%20frameworks%20are,DOM%20APIs%20for%20setting%20styles%20updating%20content%2C%20etc.)for developing web user interfaces. In addition, it is used for [mobile UI](http://www.mobileui.org/) frameworks, Android and iOS app development, and desktop programming using the electron framework. The core library for Vue is simple to incorporate into other libraries and projects. I'll go over the built-in vue.js directives in this article and show you how to create custom directives. ## What are the directives in vue.js? [Directives in Vue.js](https://www.dotnettricks.com/learn/vue/directives-in-vuejs#:~:text=The%20Vue.js%20Directives%20are%20one%20of%20the%20special,like%20hiding%2Fshow%20elements%2C%20adding%2Fremoving%20elements%2C%20and%20so%20on.) are special attributes added to [HTML elements ](https://www.w3schools.com/html/html_elements.asp)that allow you to bind data and control the behavior and appearance of an element. Directives are prefixed with the “V-” character, this prefix tells vue that the attribute is a directive and not just a regular HTML attribute. The purpose of directives is to apply dynamic behavior to the [DOM](https://www.geeksforgeeks.org/dom-document-object-model/), making it easier to manage and manipulate elements based on the application state. To use a directive in Vue.js, you simply add the directive as an attribute to the HTML element you want to modify. The value of the directive should be a JavaScript expression that returns the value or action you want to bind to the element. For example, the following code binds the value of the `message` property to the text content of a `p` element using the `v-bind` directive: ```javascript <template> <div> <p v-bind:textContent="message"></p> </div> </template> <script> export default { data() { return { message: 'Hello, World!' } } } </script> ``` ## Directives in Vue.js ### v-If [v-if ](https://vuejs.org/api/built-in-directives.html)is a vue.js directive that renders an element based on the truthiness of a javascript expression. This means you can choose to display or hide elements in your HTML based on whether a condition is true or false. It prompts transition when its condition changes. For example: ```javascript <template> <div> <p v-if="showText">This text is shown when showText is true.</p> </div> </template> <script> export default { data() { return { showText: true } } } </script> ``` In the example above, the text "This text is shown when showText is true." is displayed only when the value of showText is true. If the value of showText is false, the text will not be displayed. The `v-if` directive can also be used in conjunction with the `v-else` directive to provide an "else" branch to the conditional rendering. For example: ```javascript <template> <div> <h1 v-if="showTitle">Hello, OpenReplay!</h1> <p v-else>The title is hidden.</p> <button @click="showTitle = !showTitle">Toggle Title</button> </div> </template> <script> export default { data() { return { showTitle: true }; } }; </script> ``` In this example, the `p` element is only rendered if the `showTitle` data property is `false`. It is important to note that the `v-if` directive operates on the element it is applied to and all its children. If you want to conditionally render only a portion of the element's content, you can use the `v-if` directive on a `template` element. For example: ```javascript <template> <div> <template v-if="showTitle"> <h1>Hello, OpenReplay!</h1> <p>The title is visible.</p> </template> <template v-else> <p>The title is hidden.</p> </template> <button @click="showTitle = !showTitle">Toggle Title</button> </div> </template> <script> export default { data() { return { showTitle: true }; } }; </script> ``` In this example above, only the `h1` and `p` elements within the first `template` element are conditionally rendered, not the entire parent `div` element. The `v-if` directive is a powerful way to conditionally render elements in Vue.js. Whether you're working with a single element or a portion of an element's content, the `v-if` directive gives you the flexibility to show or hide elements based on a truthy or falsy value ### V-for [v-for](https://vuejs.org/api/built-in-directives.html) is a built-in directive in Vue.js. The v-for directive allows you to loop through an array of items and render each item in a template. Here's an example of how you might use the v-for directive in Vue: ```javascript <template> <ul> <li v-for="item in items" :key="item.id"> {{ item.text }} </li> </ul> </template> <script> export default { data() { return { items: [ { id: 1, text: 'apple' }, { id: 2, text: 'banana' }, { id: 3, text: 'cherry' } ] } } } </script> ``` In the example above, the v-for directive is used to loop through the `items` array and render each item as a list item in an unordered list. The `:key` attribute is used to provide a unique identifier for each item, which is recommended for performance reasons. The output will be: - apple - banana - cherry ### V-on The[ v-on](https://vuejs.org/api/built-in-directives.html) directive in Vue.js is used to attach [event listeners](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener) to DOM elements. It allows you to bind JavaScript event handlers to DOM events, such as click, input, and more. Below is an example: ```javascript <template> <div> <button v-on:click="incrementCounter">Click me</button> <p>You have clicked the button {{ counter }} times.</p> </div> </template> <script> export default { data() { return { counter: 0 }; }, methods: { incrementCounter() { this.counter++; } } }; </script> ``` In the above example, the `v-on:click` directive listens to the `click` event on the button element and triggers the `incrementCounter` method when the button is clicked. The `v-on` directive can be written as an abbreviation using the `@` symbol: ``` <button @click="incrementCounter">{{ counter }}</button> ``` You can also use `v-on` to listen to multiple events by passing an object with multiple event listeners: ```javascript <template> <input v-on="{ input: updateValue, focus: focusHandler, blur: blurHandler }" /> </template> <script> export default { data() { return { value: '' }; }, methods: { updateValue(event) { this.value = event.target.value; }, focusHandler() { console.log('Focus event'); }, blurHandler() { console.log('Blur event'); } } }; </script> ``` In this example, the `v-on` directive is used to attach multiple event listeners to an input element. The `input` event listener is used to update the `value` data property with the value of the input, while the `focus` and `blur` event listeners are used to log messages to the console. Whether you're working with a single event or multiple events, `v-on` makes it easy to respond to user interactions in your Vue.js app. ### V-model The [v-model](https://vuejs.org/api/built-in-directives.html) directive in Vue.js is used to bind values of an input element to a data property in the Vue instance. The v-model directive creates a two-way data binding, meaning that changes made in the input element will automatically update the data property, and vice versa. Here's an example: ```javascript <template> <div> <input v-model="message"> <p>{{ message }}</p> </div> </template> <script> export default { data() { return { message: 'Hello OpenReplay!' } } } </script> ``` The "message" data property is bound to the value of the input element using the "v-model" directive. The "message" data property will be displayed in a paragraph below the input element. Whenever the user changes the input value, the change will be reflected in the "message" data property and displayed in the paragraph, and vice versa. V-model can also be used with other input elements, such as checkboxes and radio buttons, to bind a value to a data property: ```javascript <template> <input type="checkbox" v-model="isChecked" /> <span v-if="isChecked">Checked</span> <span v-else>Not checked</span> </template> <script> export default { data() { return { isChecked: false }; } }; </script> ``` In this example, the `v-model` directive is used to bind the value of a checkbox to the `isChecked` data property. When the checkbox is checked or unchecked, the `isChecked` data property is updated, and the text displayed by the `span` elements changes accordingly. The `v-model` directive is a convenient way to bind values to inputs in your Vue components, and it eliminates the need to manually update the input value and the data property every time one of them changes. ### V-else The [v-else](https://vuejs.org/api/built-in-directives.html) directive in Vue.js is used in conjunction with "v-if" and "v-else-if" directives to conditionally render elements based on the truthiness of an expression. The v-else directive specifies the template to render when the expression passed to the "v-if" directive is falsy. The "v-else" directive must be placed immediately after a "v-if" or "v-else-if" directive. It can be used to show or hide elements, components, or any other content within the DOM. Here's an example: ```javascript <template> <div> <p v-if="showMessage">{{ message }}</p> <p v-else>No message to display.</p> </div> </template> <script> export default { data() { return { showMessage: false, message: 'Hello OpenReplay!' } } } </script> ``` In this example, the value of the "showMessage" data property determines whether the message is displayed or not. If "showMessage" is truthy, the message will be displayed, otherwise the text "No message to display" will be displayed. ### V-bind The [v-bind](https://vuejs.org/api/built-in-directives.html) directive in Vue.js is used to bind values of an HTML attribute to a data property in the Vue instance. The v-bind directive creates a one-way data binding, meaning that changes made in the data property will automatically update the value of the HTML attribute, but changes made in the HTML attribute will not affect the data property. For example: ```javascript <template> <div> <img v-bind:src="imageSrc"> </div> </template> <script> export default { data() { return { imageSrc: 'https://picsum.photos/200' } } } </script> ``` The "imageSrc" data property is bound to the "src" attribute of an image element using the "v-bind" directive. Whenever the value of the "imageSrc" data property changes, the change will be reflected in the "src" attribute of the image element and update the image displayed. ### V-once The [v-once](https://vuejs.org/api/built-in-directives.html) directive in Vue.js is used to indicate that a component should render its content only once, and that its content should not change even if the data changes. Here is an example: ```javascript <template> <div v-once>{{ message }}</div> </template> <script> export default { data () { return { message: 'OpenReplay is awesome!' } } } </script> ``` In the example above, the message "OpenReplay is awesome!" will be displayed once and will not update even if the data changes. V-once is useful when you want to display static content that does not need to change, such as a disclaimer or a copyright notice. It can also be useful for performance optimization, as it prevents the DOM from re-rendering the content every time the data changes. ## Creating custom directives [Custom directives](https://vuejs.org/guide/reusability/custom-directives.html#introduction) in Vue.js allow you to extend the functionality of the template language. To create a custom directive, you need to use the `directive` method on the Vue instance or a component. Here is an example of how to create a custom directive in Vue.js: ```javascript // main.js const app = new Vue({ el: '#app', directives: { custom: { bind(el, binding, vnode) { el.style.color = binding.value; } } } }); ``` ```htmlembedded <!-- index.html --> <div id="app"> <p v-custom="'red'">This text will be red.</p> </div> ``` In the above example, the custom directive `v-custom` changes the color of the text to red. The `bind` function is called when the directive is bound to an element, and it receives the element, the binding object, and the Vue virtual node as arguments. You can also create more complex custom directives with logic in JavaScript, for example: ```javascript // main.js const app = new Vue({ el: '#app', directives: { custom: { bind(el, binding, vnode) { const fontSize = binding.value || 14; el.style.fontSize = `${fontSize}px`; } } } }); ``` ```htmlembedded <!-- index.html --> <div id="app"> <p v-custom="18">This text will have a font size of 18px.</p> <p v-custom>This text will have a font size of 14px.</p> </div> ``` In this example, the custom directive `v-custom` changes the font size of the text. If a value is passed to the directive, it sets the font size to that value. If no value is passed, it sets the font size to 14px. ## Conclusion Directives in Vue provide a powerful way to manipulate HTML elements and extend their functionality. whether you are using built-in directives or creating custom ones, they are an essential part of the vue.js framework and are used in almost all vue.js applications. Custom directives can be used to extend the functionality of HTML elements.

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully