What causes the undefined value of "this" in the Vue Composition API setup function?

A Vue component I've created is using v3's composition API:

<template>
  <input type="checkbox" v-model="playing" id="playing" @input="$emit('play', $event.target.value)" />
  <label for="playing" >{{ playing ? 'Pause' : 'Play' }}</label>
</template>
<script>
export default {
  props: {
    done: Boolean
  },
  setup(props) {
    const playing = ref(true)
    watchEvent(() => {
      if (props.done) {
        playing.value = false
        this.$emit('play', playing.value)
      }
    }
    return { playing }
  }
}
</script>

After running the watchEvent, an error occurs stating

Cannot read property "$emit" of undefined
. It seems like the issue isn't related to the function type being used (arrow or normal).

It appears that this remains undefined within the setup() function regardless of whether it's a regular function or an arrow function.

Answer №1

When working with the Vue Composition API, the setup function receives two important arguments: props and context.

The context argument plays a crucial role as it provides access to a select list of properties that were previously available through this in 2.x APIs:

const MyComponent = {
  setup(props, context) {
    context.attrs // Previously this.$attrs
    context.slots // Previously this.$slots
    context.emit // Previously this.$emit
  }
}

It's worth noting that while you shouldn't destructure props (as it will result in losing reactivity), it is acceptable to destructure context.

For example, in the code snippet provided, you can use setup(props, { emit }) and then replace this.$emit with emit.

Answer №2

When working with the Vue 3 Composition API, it is important to note that the methods for accessing the router have changed according to the official documentation:

Previously, we used to access router instances using this.$router or this.$route directly. However, in Vue 3 Composition API, we now utilize the functions useRouter and useRoute:

import { useRouter, useRoute } from 'vue-router'

export default {
  setup() {
    const router = useRouter()
    const route = useRoute()

    function navigateWithQuery(query) {
      router.push({
        name: 'search',
        query: {
          ...route.query,
          ...query,
        },
      })
    }
  },
}

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

Transforming Ember's ajax query string

Using ember-model, I am making a request like this: App.Video.find({'sort':'createdAt+asc'}); to retrieve a sorted list of videos. This should result in the following request: http://localhost:1337/api/v1/videos?sort=createdAt+asc How ...

Tips on how to properly format a DateTime String

I need help with formatting a DateTime string retrieved from an API where it is in the format of YYYY-MM-DDTHH:MM:SS +08:00 and I want to change it to DD-MM-YY HH:MM getDataFromApi(res) { this.timestamp = this.timestamp.items[0].timestamp; console ...

Turn off all VuetifyJS transitions

Is there a way to completely turn off all transitions, such as the slide-x-transition or dialog modal scale transition, in VuetifyJS? ...

ng-table Filtering with dropdown selection

Hello, I am currently working on creating a Ng-table with a select dropdown menu for filtering the results. Here is where I am at so far. 1) How can I remove one of the pagination options that appear after applying the filter? I only want to keep one pagi ...

What is the best way to send the image location to a child component in Vue?

Having trouble displaying my image for some reason. I have the image path sent to the component for rendering, but it just won't show up. I am using Vue-CLI for this project. This is how my folders are structured: src | App.vue | bulbasaur.png | / ...

Struggling to access a remote URL through jQuery's getJSON function with jsonp, but encountering difficulties

Currently, I am attempting to utilize the NPPES API. All I need to do is send it a link like this and retrieve the results using jQuery. After my research, it seems that because it is cross-domain, I should use jsonp. However, I am facing difficulties m ...

What methods are typically used for testing functions that return HTTP observables?

My TypeScript project needs to be deployed as a JS NPM package, and it includes http requests using rxjs ajax functions. I now want to write tests for these methods. One of the methods in question looks like this (simplified!): getAllUsers(): Observable& ...

Develop a Vue mixin to enable theme switching in a Vue.js application

I have successfully developed three distinct themes: light, default, and dark. Currently, I am working on implementing a toggle function in the footer section that allows users to switch between these themes effortlessly. Following the guidance provided b ...

Creating a personalized cover for devextreme column in datagrid: A Step-by-Step Guide

I have encountered an issue with wrapping a Column inside my DataGrid. My goal is to create a customized component that generates a Column with the correct formatting. For instance, I want to develop a ColumnDate component that includes specific date forma ...

Google Cloud's implementation of the "Vue+S3+Lambda" architecture

My VueJs single page website currently has very few transactions, prompting me to explore implementing it with a serverless architecture. One recommended approach for a basic Web Application on AWS includes: Vue App uploaded on AWS S3 Backend connection ...

Are there any alternatives to ui-ace specifically designed for Angular 2?

I am currently working on an Angular2 project and I'm looking to display my JSON data in an editor. Previously, while working with AngularJS, I was able to achieve this using ui-ace. Here is an example of how I did it: <textarea ui-ace="{ us ...

Fixing the "Package Manager Not Found" Issue when Deploying a Next.js Project on Vercel

Having created a website using Next.js and aiming to deploy it on Vercel, I encountered an error during the deployment process despite meticulously following the configuration steps. The error message displayed was: "Unable to determine package manage ...

Is there a way to easily access the automated departure range feature of a date

I apologize if my question seems too simple, but I am having trouble understanding JavaScript. My issue pertains to a range datepicker where I want the departure picker to automatically open when the arrival is selected. Here's the JavaScript code I h ...

When no values are passed to props in Vue.js, set them to empty

So I have a discount interface set up like this: export interface Discount { id: number name: string type: string } In my Vue.js app, I am using it on my prop in the following way: export default class DiscountsEdit extends Vue { @Prop({ d ...

Using React.js to create a modal that includes ExpansionPanelDetails with a Checkbox feature

I am trying to achieve a specific visual effect with my code. Here is an example of the effect I want: https://i.stack.imgur.com/cJIxS.png However, the result I currently get looks like this: https://i.stack.imgur.com/547ND.png In the image provided, y ...

Guide on running a MySQL query in an asynchronous function in a Node.js application

Encountering some challenges while using MySQL in a node/express JS application. It seems that when trying to access the MySQL database within an asynchronous function, the code will 'skip over' the SQL query and run synchronously. This is the co ...

What is the best way to change the status of a disabled bootstrap toggle switch?

I'm working with a read-only bootstrap toggle that is meant to show the current state of a system (either enabled or disabled). The goal is for it to update every time the getCall() function is called. However, even though the console logs the correct ...

The ajax success() function is failing to function properly when attempting to make a call

The button's onClick() event is not navigating anywhere. There seems to be an issue with the success() function of the ajax call. Unfortunately, I am new to this and unable to pinpoint the problem. var currentAuthor=""; var currentQuote=""; $(documen ...

The radio button element could not be located using the attribute "checked="Checked""

While working with Geb, I encountered an issue using the code div.find("input","checked":contains("checked")). This is the snippet of code I attempted to use in order to locate the checked radio button on a webpage. However, I received an error when using ...

Whenever I press a button, my desire is for each picture to seamlessly reposition itself in the exact same spot on the screen

Having some issues with my code. When I click a button, the plan is for the pictures to change one by one to simulate a traffic light sequence. However, when I run the code, all the pictures appear at once without any effect from the button. Any help in ac ...