简体   繁体   中英

Vue.js - How to get “this” object in componenet?

console.log(this) in doSomthing method, it is displayed "null".

I thought of console.log(this.currentPage) is displayed "main" but "this" object is null.. :(

How to access "main" of 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="doSomthing">
                {{ 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
                    }
                ],
                doSomthing: function(e){
                    console.log(this)
                }
            };
        },
        method: {
        },
        computed: {
        }
    };
</script>

I think data() should only have the state of your component, no actions. Try moving your doSomething to methods in your component, like:

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM