Can you explain the significance of the v-on="..." syntax in VueJS?

While browsing, I stumbled upon a Vuetify example showcasing the v-dialog component. The example includes a scoped slot called activator, defined like this:

<template v-slot:activator="{ on }">
  <v-btn
    color="red lighten-2"
    dark
    v-on="on"
  >
    Click Me
  </v-btn>
</template>

Although I grasp the concept of scoped slots from VueJS documentation and understand destructuring slot props, I am puzzled by the meaning of v-on="on" in this example. Specifically, what does it imply when the event is not explicitly named with the v-on directive?

The VueJS documentation on v-on only demonstrates its usage alongside a specified event name (e.g., v-on:click="..."), without explaining the scenario of using just v-on="...".

Could someone shed some light on this syntax and its application in the context of the Vuetify example?

Answer №1

Summary:

basic usage

<!-- object syntax (2.4.0+) --> 
<button v-on="{ mousedown: doThis, mouseup: doThat }"></button>]

In a nutshell, @click="..." is equivalent to v-on:click="..." which is the same as v-on="{click:...}"


Summary:

vuetify implementation:

genActivator () {
      const node = getSlot(this, 'activator', Object.assign(this.getValueProxy(), {
        on: this.genActivatorListeners(),
        attrs: this.genActivatorAttributes(),
      })) || []

      this.activatorNode = node

      return node
    }

Insightful information:


This approach proves useful when abstracting components and passing multiple listeners at once instead of writing separate assignment lines.


export default {

  data() {
    return {
      on: {
        click: console.log,
        contextmenu: console.log
      },
      value: "any key value pair"
    }
  }
}
<template>
  <div>
    <slot name="activator" :on="on" :otherSlotPropName="value" >
      <defaultComponent v-on="on" />
    </slot>
  </div>
</template>

By using the component above, slot properties can be accessed and passed into custom components like so:

<ExampleComponent>
  <template v-slot:activator="{ on, otherSlotPropName }">
    <v-btn
      color="red lighten-2"
      dark
      v-on="on"
    >
      Click Me
    </v-btn>
  </template>
 <ExampleComponent />

Easier visualization with plain Javascript:

Comparing the previous component - utilizing render function rather than template:

export default {

  data() {
    return {
      on: {
        click: console.log,
        contextmenu: console.log
      },
      value: "any key value pair"
    }
  },
  render(h){

    return h('div', [
      this.$scopedSlots.activator &&
      this.$scopedSlots.activator({
        on: this.on,
        otherSlotPropName: this.value
      })
      || h('defaultComponent', {
        listeners: this.on
      }
    ]
  }
}

Exploring the source code:

If a blank v-on="eventsObject" argument is present, the method bindObjectListener will be invoked to assign events to data.on.

This process occurs within the createComponent realm.

Subsequently, the listeners are updated via updateListeners as VNodeComponentOptions.


Vue extension in Vuetify's context - an in-depth look into the implementation:

By merging and extending Vue instances, any component can be reduced into a more modular form.

Vuetify demonstrates this concept through components like v-dialog by incorporating an activator mixin.

Examining the content of on mounted by the activatable yields:

const simplyfiedActivable = {

  mounted(){
    this.activatorElement = this.getActivator()
  },
  watch{
    activatorElement(){
      // if el exists
      this.addActivatorEvents()
    }
  },
  methods: {
    addActivatorEvents(){
      this.listeners = this.genActivatorListeners()
    },
    genActivatorListeners(){
      return {
        click: ...,
        mouseenter: ...,
        mouseleave: ...,
      }
    },
genActivator () {
      const node = getSlot(this, 'activator', Object.assign(this.getValueProxy(), {
        on: this.genActivatorListeners(),
        attrs: this.genActivatorAttributes(),
      })) || []

      this.activatorNode = node

      return node
    },
  }
}

To implement the above logic into an actual component, consider:

// Usage of Vuetify mixins for implementation
const baseMixins = mixins(
  Activatable,
  ...other
)

const sympliefiedDialog = baseMixins.extend({
  ...options,
  render(h){
    
    const children = []
    children.push(this.genActivator())
    return h(root, ...options, children)
  }
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I show the table row as an inner table row when the first field is identical?

<tr ng-model="check" ng-repeat="orderBook in orderBookDetails| orderBy: 'orderBook.no'" value='check=$scope.orderBookDetails.sowNo'> <td ng-if='check!=orderBook.no'>{{orderBook.no}}</td> <td>{{order ...

Self-reference within a JavaScript object involves creating a property that points

Can you reference another part of a JSON object within the same JSON object? In the code snippet below, there is an object that refers to the "home" object within the "MapParameters" object. { "parameters": { "data": { "URL": "http://SC.json ...

Is there a way to modify the variable in order to switch the font of the heading every second using CSS and JavaScript?

I'm trying to create a heading that changes fonts every second, but I'm having trouble changing the variable to set it to another font. Check out my code here. Despite watching tutorials, everything seemed too confusing. var root = document.q ...

Managing data in React and JavaScript: Clearing fields upon successful sign up and redirecting to login page after receiving a 200 status code

Here is the code for my SignUp react function. After receiving a response of 200 upon clicking the Sign up button, I want to clear the text in all three fields and redirect the user back to the login page. I'm new to web development so any assistance ...

Issue encountered while transforming the data buffer into the video within a Node.js environment

I am attempting to create a buffer from the mp4 video, and then convert that buffer back into the video. The buffer is being generated as follows: const buffer = Buffer.from("Cat.mp4"); console.log(buffer); The output I receive is <Buffer 43 61 74 2e ...

What is the method for determining the size of a WeakMap?

I am working with a WeakMap that looks like the following: let newObj = new WeakMap(); let key1={"a":1}; let key2={"b":2}; let key3={"c":3}; newObj.set(key1,"value1"); newObj.set(key2,"value2"); newObj.set( ...

Obtain a custom token after next authentication through Google login

Utilizing next js, next auth, and a custom backend (flask), I have set up an API Endpoint secured with jwt token. In my next js frontend, I aim to retrieve this jwt token using the useSession hook to send requests to these API Endpoints. Everything functio ...

A captivating opportunity for a web developer specializing in frontend design

Encountered an intriguing dilemma that has me stumped. There is a single stipulation: Only the json can be altered! I am struggling to meet this requirement: data.hasOwnProperty("\u{0030}") class JobHunter { get data() { return &ap ...

The delete function is not functioning

I need help with implementing a custom Angular directive that includes a delete button to remove itself. When I click the button removeMe, it is not deleting an item from the array. Any suggestions on what might be causing this issue? HTML: <button t ...

Incorporate radio buttons to toggle the visibility of div elements within Vue 3

In my current Vue 3.0.5 project, I am trying to toggle between different <div> elements using radio buttons, allowing only one element to be shown at a time. Interestingly, I noticed that when I include the v-bind directive before the value attribute ...

Tips for Setting up SQLite Database Connection in VueNative App

Struggling to establish a connection to SQLite database in vueNative. Unsure of the steps to take. Could someone lend a hand? Seeking guidance on how to connect to SQLite db within a vueNative app. ...

Deploy quickly using Vite on Azure Devops

We are facing a challenge while deploying our new Vite +Vue3 application to the server. The issue lies with our outdated yaml file, which still includes a "--dest" option from our previous Vue 2 CLI deployment. Is there anyone familiar with how to specify ...

The React application is experiencing difficulties in receiving the response data (JSON) from the Express server, despite the fact that

When making POST or GET requests to our Express server, served through PM2 on EC2, Postman receives the complete response with JSON data. However, our front end React app (both locally and deployed via CF) only gets the response status code and message. Th ...

Callback function triggered upon the creation of a DOM node

I am in search of a way to have a specific callback function run each time a div that matches a particular selector is added to the DOM. I have explored the DOM events documentation and the event closest to what I need seems to be "load", however, it does ...

Problem with routing: Request parameters not being collected

I am currently working on a project to create a wikipedia clone. Initially, I set up an edit route that looks like this: router.get('/edit/:id', function(req, res){ var id = req.params.id; console.log(id); models.Page.findById(id, ...

Error message in JavaScript saying "The response string is undefined

I am working on a program built in angularjs. Currently, I receive JSON data from the server when online, but I am now developing an offline mode for the application. Despite trying to tackle the issue, I am unable to identify why I cannot resolve it. In ...

Can you explain the functionality of this Sample AngularJS Infinite Scroll feature?

I stumbled upon this AngularJS script while searching for some samples, but I'm having trouble understanding the angular module and directive aspects of the code. However, I did manage to modify the loadMore() function to fetch a JSON resource from my ...

Attempting to route a selector, yet on the second attempt, the entity is successfully transferred

I am currently working on developing a function that will switch the image every half second for 10 iterations. During the final iteration, the image src will be set to the actual value. Everything seems to work fine for the first loop, however, when the s ...

In ReactJS, when passing an array of objects to a child component, the first instance may sometimes return as undefined, causing the code to break

Currently, I am in the process of creating a personal blog for my brand. The "Posts" section is designed to retrieve data from a basic JSON via an API. At present, I have used mirageJS to mock the API and employed the useEffect and useState hooks to set th ...

Is there a way to automatically close the Foundation topbar menu when a link is selected?

On my single page website, I am utilizing Zurb Foundation's fixed topbar which includes anchor links to different sections of the page. My goal is to have the mobile menu close automatically whenever a link inside it is clicked. As it stands now, whe ...