How can I call method from data on vue.js?

samuel toh picture samuel toh · Oct 27, 2017 · Viewed 17.8k times · Source

My vue component like this :

<template>
    ...
        <ul class="nav nav-tabs nav-tabs-bg">
            <li v-for="tab in tabs" role="presentation" :class="setActive(tab.url)">
                <a :href="baseUrl + tab.url">{{tab.title}}</a>
            </li>
        </ul>
    ...
</template>

<script>
    export default {
        props: ['shop'],
        data() {
            return{
                tabs: [
                    {
                        title: 'product',
                        url: '/store/' + this.shop.id + '/' + strSlug(this.shop.name)
                    },
                    {
                        title: 'info',
                        url: '/store/' + this.shop.id + '/' + strSlug(this.shop.name) + '/info'
                    }
                ]
            }
        },
        methods: {
            setActive(pathname){
                return {active: window.location.pathname == pathname}
            },
            strSlug: function(val) {
                return _.kebabCase(val)
            }
        }
    }
</script>

If the code run, there exist error like this :

[Vue warn]: Error in data(): "ReferenceError: strSlug is not defined"

If I console.log(window.location.pathname), the result like this :

/store/21/chelsea-hazard-store

So if it is the same as url with data in tabs, then it will active

I call the strSlug method to convert each into lowercase and convert spaces into -

Seems it can not call the method from the data

How can I solve the error?

Answer

The Guy with The Hat picture The Guy with The Hat · Oct 27, 2017

When accessing data or methods from within the vue object, use this.thing. In your case, that would be this.strSlug(this.shop.name).