Accessing the "this" object in Vue.js components

When executing console.log(this) in the doSomething method, it returns "null".

I was expecting console.log(this.currentPage) to display "main", but unfortunately, the "this" object is null.. :(

Is there a way to access the value of "main" for currentPage?

<template>
    <div class="tab_menu_wrap">
        <ul class="tab_menu">
            <li v-for="tab in tabMenus" v-bind:class="{ active: tab.isActive }" v-on:click="doSomething">
                {{ tab.text }}
            </li>
        </ul>
    </div>
</template>

<script>
    export default {
        name: 'tab-menu',
        props: {

        },
        data() {
            return {
                currentPage: "main",
                isActive: true,
                tabMenus: [
                    {
                        text: 'A',
                        isActive: true
                    },
                    {
                        text: 'B',
                        isActive: false
                    },
                    {
                        text: 'C',
                        isActive: false
                    }
                ],
                doSomething: function(e){
                    console.log(this)
                }
            };
        },
        method: {
        },
        computed: {
        }
    };
</script>

Answer №1

I believe that the data() function should only contain the state of your component, without any actions. You should consider moving your doSomething action to the methods section of your component code:

<template>
    <div class="tab_menu_wrap">
        <ul class="tab_menu">
            <li v-for="tab in tabMenus" v-bind:class="{ active: tab.isActive }" v-on:click="doSomething">
                {{ tab.text }}
            </li>
        </ul>
    </div>
</template>

<script>
    export default {
        name: 'tab-menu',
        props: {

        },
        data() {
            return {
                currentPage: "main",
                isActive: true,
                tabMenus: [
                    {
                        text: 'A',
                        isActive: true
                    },
                    {
                        text: 'B',
                        isActive: false
                    },
                    {
                        text: 'C',
                        isActive: false
                    }
                ]
            };
        },
        methods: {
                doSomething: function(e){
                    console.log(this)
                }
        },
        computed: {
        }
    };
</script>

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

Exploring the wonders of Jasmine coding with jQuery

I am relatively new to conducting Jasmine tests. I have a basic understanding of how to install it and use simple commands like toEqual, toBe, etc. However, I am unsure of how to write test code for this particular jQuery function using Jasmine. if ($(&ap ...

Is there a way to display session messages in a CakePHP .ctp file?

There is a button on a view page that requires validation to check the type of user clicking it. We want to restrict certain users from clicking this button and making changes. To achieve this, we are checking the session ID at the time of button click. If ...

Having difficulty updating the parent for all PortfolioItem/Feature that were copied for a specific PortfolioItem/MMF

I'm facing a challenge in setting the parent for multiple features that I've copied for a specific MMF. However, only the parent of the last feature is being set. Below is the code snippet responsible for setting the parent: Record represents th ...

Tips for extracting data from cells within an HTML table using JavaScript

I am looking to extract the values from a cell of an HTML table in order to store them in a MySQL table using PHP. I prefer to utilize JavaScript instead of jQuery. I have assigned a unique ID to each TR based on the ID field in the MySQL table. Additiona ...

Identify compatibility with the background-attachment property set to fixed

I've been searching for an updated answer on this topic, but I couldn't find one so I wanted to confirm. My goal is to achieve a parallax effect using background-attachment: fixed, however I've noticed that it doesn't work on mobile ph ...

Obtain headers from receiving an external JavaScript file

I am trying to find a way to import an external .js file and access the response headers from that request. <script src="external/file.js?onload=callback"> function callback(data) { data.getAllResponseHeaders(); } </script> Unfortunately, ...

Tips for validating a form's input on an ajax page with the help of jQuery

I am facing an issue with a form containing two inputs. The first input can be validated before triggering an ajax function, but the second input cannot be validated. The second input is loaded from a page using ajax, along with the submit button. I need t ...

I'm encountering an error when trying to use makeStyles

Something seems off with MUI. I was working on my project yesterday and makeStyles was functioning properly, but now it's suddenly stopped working. I'm encountering an error when calling it here: https://i.sstatic.net/tBf1I.png I suspect the iss ...

Issue with ng-grid in AngularJS: Data does not appear after resizing columns

Currently, I am encountering a problem where ng-grid data is not being displayed when column resizing occurs after changing the column names. To demonstrate this issue, I have created a plunkr at - http://plnkr.co/edit/eV9baoDOV9A46FZmKW8G?p=preview I wo ...

execute bower install for the specified bower.json file

Let's say my current working directory is c:\foo\ while the script is running. I want to execute bower from there for the c:\foo\bar\bower.json file. This can be done in npm by using npm install --prefix c:\foo\bar. ...

How can I extract data from an XML file and include it in a JSON file using GulpJS?

Being relatively inexperienced with Gulp/Node programming, I am facing some difficulties while trying to accomplish a simple task :) Within my XML file, there exists a node like the following: <widget version="1.1"></widget> My goal is to ext ...

Redirecting to a hash in Vue-router with a specified timeout

My route configuration looks like this: { path: '/kontakt', redirect: '#contact', component: index }, as well as the scroll behavior: scrollBehavior(to, from, savedPosition) { if (savedPosition) { return saved ...

How can we effectively implement conditional rendering when dealing with components that are nearly identical?

Depending on whether the user is a professor, student, or not logged in, I render different landing pages. The landing pages are quite similar, with the only distinction being the buttons displayed. While I could easily achieve this using inline conditions ...

Encountering a NextJS error with head component

Trying to incorporate the head element into a NextJS page format has proven challenging. Despite consulting the official documentation, implementing next/head to add <head> has resulted in an error within the code block. Code: import Head from &apos ...

What is the significance of Fawn's statement, "Invalid Condition"?

Despite following the instructions and initiating Fawn as stated in the document, I'm still encountering an error message that says Invalid Condition. Can anyone help me identify what is causing this issue? Thank you to all the helpers. await new Fawn ...

Tips for integrating Typescript into a pre-existing Vue 3 project

The contents of my package.json file are as follows: { "name": "view", "version": "0.1.0", "private": true, "scripts": { "serve": "vue-cli-service serve" ...

The basic function is ineffective when used within an if-condition

I am currently dealing with a JSON file that has some nesting: { "name": "1370", "children": [ { "name": "Position X", "value": -1 }, {...} ] "matches": [ { "certainty": 100, "match": { "name": "1370 ...

Live tweet moderation made easy with the Twitter widget

Currently in search of a widget, jQuery plugin, hosted service, or equivalent that can be easily integrated into an HTML page. This tool should display and automatically update live tweets featuring a specific hashtag, only from designated accounts set by ...

Looking to incorporate an additional column 'LastName' that can be used for filtering in the Angular data table code. This column will be included if it is present in the data

function applyFilter(filterValue: string) { filterValue = filterValue.toLowerCase(); --- return filtered result return this.dataSet.filter( (item: any) => item.name ? item.name.toLowerCase(). ...

Error Message: ElectronJS - Attempted to access the 'join' property of an undefined variable

I am currently working on developing a tray-based application. However, I am encountering an error that reads: Uncaught TypeError: Cannot read property 'join' of undefined Can anyone guide me on how to resolve this issue? This is the content ...