Looking to receive child events within a Vue 3 setup()?

Looking to convert the code below to use Vue 3 composition API.

I am trying to listen for an event from a child component in a parent component that utilizes the render function. In Vue 3, $on has been removed and I'm unsure of how to replace it in the setup method.

created() {
    this.$on('update-visibility', this.updateElementBounds);
  }

Context Example

  // ...
  methods: {
    updateElementBounds() {
      const {offsetTop, offsetHeight} = this.$el;
      this.elementTop = offsetTop;
      this.elementHeight = offsetHeight;
    },
  },

  created() {
    this.$on('update-visibility', this.updateElementBounds);
  },

  render() {
    const {isPageFocused, isElementFocused} = this;
    return this.$scopedSlots.default({
      isPageFocused,
      isElementFocused,
    });
  },

Answer №1

The setup function in the composition API does not have direct access to the DOM.

To listen to events emitted by a child component, use the v-on directive in the template. Set the desired function as the value to be called when the event is triggered.

<child v-on:toggleVisibility="updateElementStyle"></child>

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

Creating movement in three distinct divisions

I am seeking a way to have three divs flying in upon click. The first DIV is positioned at the top, followed by one on the left and one on the right (both being below the top one). I wish for them to fly in from their respective directions - the top div fr ...

Encountered a vue variable error while running db.each function

Recently, while working with ElectronJS, SQLite3, and Vue.js, I encountered an error message saying "undefined this.tb" when trying to use the `tb.push` method within `db.each`. Surprisingly, I was able to fix it without fully understanding why. The code ...

Clearing form data after submitting in Laravel using axiosIn Laravel, utilizing

When working on my Laravel app, I encountered an issue while submitting a form using Vue and Axios. Despite my attempts to clear the input field after submission, it doesn't seem to work. HTML: <form method="post" enctype="multipart/form-data" v- ...

What is the method to trigger a function upon opening an anchor tag?

When a user opens a link in my React app, I need to send a post request with a payload to my server. My current strategy involves using the onClick and onAuxClick callbacks to handle the link click event. However, I have to filter out right-clicks because ...

Understanding JavaScript Prototypal Inheritance within ES5 Classes

I've been working on creating an XMLHttpRequest interceptor for Angular, encountering a roadblock when trying to intercept a third-party library that uses the XMLHttpRequest API. Although the solution below is functional, I've run into issues wit ...

What are the potential drawbacks of relying heavily on socket.io for handling most requests versus using it primarily for pushing data to clients?

Is it advisable to switch AJAX routes (called with $.Ajax in jquery) like: GET /animals GET /animals/[id] POST /animals To socket.io events (event bound on client and server for client response): emit("animals:read") emit("animals:read", {id:asdasd}) ...

Make sure to always send back JSON data when using the default error handler in ExpressJS

I'm in the process of developing an API server using ExpressJS. I want to guarantee that the server consistently delivers JSON data rather than HTML data. While I can easily make the server respond with JSON for all customized routes, I encounter diff ...

What steps are necessary to activate javascript in HTML for WebView?

I recently discovered that when my HTML/JavaScript site is visited via an Android webview, JavaScript is disabled by default. This causes a pricing list on my page to not display properly because it requires a JavaScript class to be added for it to open. I ...

Resource Jump.js could not be loaded

Although I am still new to NPM, I have mostly built websites without using it. Recently, I decided to implement smooth scroll using Jump.js. Initially, everything seemed to work well when I used the live server extension in VScode. However, once I uploade ...

Leverage the power of the React useFetch hook with an onclick/event

My component utilizes a custom reusable hook for making HTTP calls. Here is how I am using it: const { data, error, isLoading, executeFetch } = useHttp<IArticle[]>('news', []); Additionally, within the same component, there is a toggle che ...

What is the best way to modify an Li element using the DOM in JavaScript?

Just the other day, I discovered how to use JavaScript and DOM to add and delete Li elements. Now I'm curious about how to edit those Li elements using DOM. Any suggestions? Thank you! ...

Preserve the previous and current state within a React application

Within my code, there is a state called newuser that undergoes changes based on the inputs entered into the input fields. This change occurs once all input fields are filled and the submit button is clicked. The goal I have in mind is to store the current ...

Stop clicks from interfering with dragging in three.js

My GLTF model in Three.js has objects within it, and I want the camera to zoom in on an object when the user clicks on it. However, I am facing an issue where if the user drags after clicking on an object, a click is triggered upon releasing the mouse butt ...

Tool to stop automatic logouts on websites

In the web application where I work, users are automatically logged out after a period of inactivity. Unfortunately, I am unable to control this feature. The code responsible for logging the user out is as follows: var windoc = window.document; var timeou ...

End the dialogue that relies on information from the Vuetify store

I have a modal dialog that pops up whenever I receive an error message from an API, but I'm facing difficulty in closing it. I am using Vuetify for this purpose. Here is the template code: <v-dialog v-model="isLoginFailed" hide-overlay p ...

Encountered a React error stating: `TypeError: this.state.projects.map is not a

export default class Timeline extends Component{ state = { projects : [], }; async componentDidMount(){ const response = await api.get("/projects"); this.setState({projects: response.data}); } render(){ return ( <div className ...

What is the best way to transfer the data from one JavaScript object to a new, empty object?

My Angular site requires a JavaScript object (JSON retrieved from a database) to display widgets: [{'widget_id':'1','widget_name':'Blue Widget','widget_description':'A nice blue widget','wid ...

Can someone explain the meaning of the paragraph in the "Index Routes" section of the React-Router documentation?

Lesson 8 of the React-Router tutorial delves into the concept of "Index Routes", outlining the importance of structuring routes in a specific way. Here are some key points from their discussion: The tutorial suggests that while setting up the initial rout ...

Monitor and refresh the Vue Nuxt api directory

Is there a way to make Nuxt watch for "non standard" directories and automatically recompile/reload itself, especially for directories containing additional server APIs? For example, I have my express API in ~/api/. Even though I reference this directory ...

"Mastering the art of traversing through request.body and making necessary updates on an object

As I was reviewing a MERN tutorial, specifically focusing on the "update" route, I came across some interesting code snippets. todoRoutes.route('/update/:id').post(function(req, res) { Todo.findById(req.params.id, function(err, todo) { ...