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

Vue (Gridsome) App encountering 'Cannot POST /' error due to Netlify Forms blocking redirect functionality

Currently, I am in the process of developing my personal website using Gridsome. My goal is to incorporate a newsletter signup form through Netlify Forms without redirecting the user upon clicking 'Submit'. To achieve this, I utilize @submit.prev ...

Exploring ways to retrieve global variables within a required() file in Node.js

Imagine having 2 files: main.js, and module.js: //main.js const myModule = require('./module'); let A = 'a'; myModule.log(); //module.js module.exports = { log() { console.log(A); } } After trying to call myModule.log, ...

Ways to access the current element in the Evernote editor that corresponds to the cursor's position?

It seems that Evernote editor uses a Rich Text Editor which differs from the input or textarea tag. Therefore, I am unable to use the provided code to determine its type. Is there a way to retrieve the current element of the Evernote editor where the curso ...

Ways to switch classes within a loop of elements in vue.js

I'm just starting to learn vue.js and I'm working on a list of items: <div class="jokes" v-for="joke in jokes"> <strong>{{joke.body}}</strong> <small>{{joke.upvotes}}</small> <button v-on:click="upvot ...

When accessing the JavaScript date object, no output is being returned

I have a calendar layout consisting of floated div elements, rather than using an actual <table>. My goal is to allow the user to click anywhere on a row to add a new booking. The challenge lies in accurately calculating the time at which they clicke ...

Can you explain the distinction between using destructuring syntax and an empty parameter when calling a render function?

After writing some code in React, I found using this.props to be too verbose. So, I researched some articles and learned how to approach this issue while coding. class MyComponent extends Component { // the traditional method render() { re ...

Receiving NaN in javascript when attempting to calculate the sum using a text input field

I am trying to calculate the total value by adding a fixed price with another value entered in a text input field. Here is the HTML code snippet: <%= f.text_field :hoursclass, id:"txt_hours" %> And here is the JS code snippet: $(function() { va ...

Uninterrupted movement within a picture carousel

Seeking a way to create a smooth transition in an image slider with sliding dividers using continuous switching when clicking previous/next buttons. Currently, the dividers replace each other from far positions. Any ideas on achieving a seamless single mov ...

Issues with JQuery Ajax rendering in browser (suspected)

I'm encountering an issue on my webpage. I have a div with two hidden fields containing values of 0 and 2, respectively. Upon clicking a button that triggers an AJAX query, the div contents are updated with hidden field values of 1 and 2. However, it ...

Exploring React-Query's Search Feature

Looking for guidance on optimizing my Product search implementation using react-query. The current solution is functional but could be streamlined. Any suggestions on simplifying this with react-query would be greatly appreciated. import { useEffect, use ...

Tips for maintaining interactivity after a page refresh

$(document).ready(function () { $("#2").click(function () { $("#content").load("{% url 'about' %}"); }); $("#3").click(function () { $("#content").load("{% url ...

What could be causing Mathjax to generate multiple copies?

I have integrated MathJax into my application to render MathML. The code snippet below is used to ensure that the MathML is typeset properly: $rootScope.$watch(function() { MathJax.Hub.Queue(["Typeset", MathJax.Hub]); return true; }); However, I ...

Help setting up Angular ng-class is needed

Hey there, I'm currently attempting to change the background color of my CSS based on the value of ng-class (true or false). Can someone help me out with this? <div id="home"> Summoner <div id="in ...

Collaborate and pass around SQL connections among different modules

One of my recently developed modules consists of three main functions: Establishing a SQL connection Executing a query Closing the connection This module is called in script.js along with other custom modules responsible for various operations that requi ...

Removing items from a list in a Vue.js application

I've encountered an issue with my code. I'm attempting to remove a "joke" from a list, but it consistently removes the joke that was inputted before the one I'm actually trying to delete. I'm struggling to identify what mistake I might ...

Using jquery to transition an image to fade out and then reappear in a different position

There is an image in a div with the highest z-index. Upon clicking on something, the image should fade out and then fade in at a specified position below another image with the class "aaa". The current approach involves using jQuery to fade out the image ...

Encountered an error when trying to access the 'modules' property of undefined in the /node_modules/bindings/bindings.js file while working with electron and setting up

1. npm install -g node-gyp 2. npm install serialport -S 3. npm install electron-rebuild -D 4. ./node_modules/.bin/electron-rebuild.cmd and after that, the rebuild process is completed. When I execute the command: npm run electron:serve, I encounter an ...

What could be causing my HTML elements to shift position based on varying screen sizes or zoom levels?

Does anyone else experience their HTML and CSS elements shifting around based on the screen size or zoom level? I have screenshots illustrating this issue. Here is how it currently appears And here is how it's supposed to look ...

When executing an $http get request in Angular, a promise is

After implementing this code in my service and noticing that it works, I have a question. Since $http.get() returns a promise which executes asynchronously, I am confused about why I need to use deffered.resolve(res.data) to return data in my service. Yo ...

When I expand the accordion next to it, the accordion disappears, and it also vanishes when I close that accordion

After incorporating accordions into my site, I encountered a peculiar issue (as shown in this video): when I open one accordion, the adjacent accordion also opens unexpectedly. Similarly, closing one accordion causes its neighboring accordion to mysterious ...