Vue.js - 如何在componentsnet中获取“this”对象?

时间:2017-05-29 13:13:24

标签: javascript vue.js

在doSomthing方法中,

console.log(this)显示为“null”。

我想到console.log(this.currentPage)显示为“main”,但“this”对象为null .. :(

如何访问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>

1 个答案:

答案 0 :(得分:0)

我认为data()应该只有组件的状态,没有动作。 尝试将doSomething移动到组件中的方法,例如:

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