The Vue component's data function is currently devoid of content

I've defined a Vue.js component as shown below:

module.exports = Vue.component('folder-preview', {
    props: ['name', 'path', 'children', 'open'],
    template: `...
    `,
    methods: mapActions([
    ]),
    computed: mapState([
    ]),
    data: ()=> {
        console.log(this);
        return {
            collapsed: (this.open !== 'true')
        }
    }
});

Essentially, my goal is to maintain collapsed as a local data property within the component while using the value passed in the prop as the initial value. However, it seems like this.open is always undefined. When I console.log this, it displays an empty object, leaving me puzzled as to why this might be happening.

Could I be misunderstanding something here?

Answer №1

The issue in your code is quite subtle: you have defined 'data' as an arrow function.

As discussed in this particular question, arrow functions fetch `this` from the context of declaration, whereas regular functions fetch `this` from the calling context. By defining 'data' as an arrow function, it won't properly access the component's scope.

When defined as a regular function that doesn't isolate `this`, the component functions correctly.

Vue.component('sample', {
  props: ['open'],
  template: '<div>{{collapsed}}</div>',
  data() {
    return {
      collapsed: this.open !== 'true'
    }
  }
})

new Vue({
  el: '#app'
})
<script src="https://unpkg.com/vue"></script>
<div id="app">
  <sample open="true"></sample>
</div>

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

Getting user information from VueJS using Axios is a common task that many developers need to tackle

Please provide guidance on what specific wording should be used in place of the following phrase? To retrieve user information from the database after logging in //ProfileDropDown.vue <template> <div class="text-right leading-tight hidden sm: ...

Tips for incorporating a favicon in a React application

Having trouble adding a favicon to my React application. I followed the instructions in this post, but it's not working for me. I placed the favicon.ico file inside the public folder where index.html resides. This is how my directory structure looks ...

Experiencing difficulties with certain npm CLI modules when using it as a task runner and build tool

After coming across an article about using npm as a build tool, I decided to give it a try for my tasks. However, I am facing an issue that has me stuck. Whenever I run a global command-line tool like JSLINT, JSHINT, or ESLINT using npm, the console always ...

Implementing a password toggle feature on a form that extends Django's default Authentication Form

Incorporating a password toggle feature has become quite the challenge as I extend Django's AuthenticationForm to create my UserLoginForm. Attempting to implement this feature has proven difficult, especially since I have been unable to make use of th ...

What are some effective ways to optimize a scrolling script?

Within my div element, I have a list of ordered elements (ol) that I am manipulating with drag and drop functionality using jQuery Nestable. If you could help me troubleshoot this issue, it would be greatly appreciated: How to scroll the window automatical ...

How to Merge Items within an Array of Objects Using Typescript?

I'm currently facing a challenge in combining objects from an array of Objects in typescript. The structure of the array is as follows: 0: {type: 'FeatureCollection', features: Array(134)} 1: {type: 'FeatureCollection', features: ...

finding the node version in a code repository

Is it possible to determine the targeted node version (4 or 6) of a Node.js application by examining its code? I'm currently reviewing this: https://github.com/jorditost/node-postgres-restapi ...

The flat function for JavaScript Arrays is not defined in React Native

I am currently developing an application using react-native and it's common knowledge that we can utilize JavaScript code in this particular project as well as any other react projects. However, whenever I attempt to use the following code snippet, t ...

The absence of CORS headers detected in XMLHttpRequest

I am currently trying to execute an ajax call to a remote server, only for developmental purposes. I have configured CORS on my server, which is why when I request the resource through the browser, it shows that the CORS headers are present. https://i.sta ...

What is the method, by using JavaScript or CSS, to include extra space at the end of text block without starting a new line?

Imagine having some text, and at the conclusion of each paragraph there is a (more)... link. The layout ends up looking like this: This is just an example paragraph. Click on the more link for additional information. (more...) Now comes the desire to i ...

Interactive Bar chart updates in real-time with Highcharts and AngularJs

With the help of a sample from Highcharts (here), I successfully integrated a bar chart into AngularJs. Below is the HTML code: <!DOCTYPE html> <html ng-lang="en" ng-app="myModule"> <head> <meta charset="ISO-8859-1"> <script sr ...

I am looking to retrieve a specific input value from a JSON array using JavaScript

I have created an array called 'PROPERTIES' which accepts values like username, password, sid, etc. I am looking to retrieve these entered values using JavaScript. 'PROPERTIES': {'gatewayurl': {'Name': ...

Instructions for saving a binary file on the client using jQuery's .post function

I am working with a handler that has the following code: HttpRequest request = context.Request; HttpResponse response = context.Response; if (request["Type"] != null) { try { string resultFile = null; ...

Mapping JSON data from Mongoose to Vue and Quasar: A comprehensive guide

I have set up a Mongoose backend and created some REST APIs to serve data to my Vue/Quasar frontend. The setup is pretty basic at the moment, utilizing Node/Express http for API calls without Axios or similar tools yet. I have successfully implemented simp ...

What could be causing my v-select to be rendered multiple times?

I am currently utilizing vuex and vuetify for my project. I want to create a dropdown list that displays items fetched from my server in the form of a Json object. These objects are returned as an array from my store, which I access using a getter in my co ...

The timer functionality in the Angular 2+ component is malfunctioning

This situation is quite perplexing. I have a timer function that works perfectly on all my components except one. Strangely, I can't seem to figure out why this particular component is not cooperating, especially since there are no error messages appe ...

Using a package with `webfontloader` in NextJs for Server-Side Rendering: A guide

Currently, I am working on creating an application with nextJS and incorporating a package that utilizes Webfontloader internally. After installing the library, my application encountered an error preventing it from running successfully. It seems like th ...

What is the best way to extract and retrieve the most recent data from an XmlHttpRequest?

Currently, I am using a web service that returns an SseEmitter to program a loading bar. The method to receive it looks like this: static async synchronize(component: Vue) { let xhr = new XMLHttpRequest(); xhr.open('PATCH', 'myUrl.co ...

Vue: The async Apollo mixin function successfully logs a value, however it ultimately returns as undefined

I've encountered numerous async/return undefined queries on this platform, but despite trying various solutions, I'm unable to make any progress. My apologies if I overlooked something obvious. In an attempt to improve reusability, I extracted a ...

What is the easiest way to identify the currently rendered Vue component in a web browser?

In the Table.vue file, both Row.vue and Form.vue are included. The desired behavior is that the table's row will indicate that it comes from the Row.vue component. I tried to investigate by right-clicking on the Row element and selecting "View page ...