如何从 vue.js 上的数据调用方法? [英] How can I call method from data on vue.js?

查看:37
本文介绍了如何从 vue.js 上的数据调用方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 vue 组件是这样的:

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 警告]:data() 中的错误:ReferenceError:strSlug 未定义"

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

如果我console.log(window.location.pathname),结果是这样的:

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

/store/21/chelsea-hazard-store

/store/21/chelsea-hazard-store

所以如果它与标签中的数据的url相同,那么它将被激活

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

我调用 strSlug 方法将每个转换为小写,并将空格转换为 -

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

好像不能从数据中调用方法

Seems it can not call the method from the data

我该如何解决错误?

推荐答案

当从 vue 对象内部访问数据或方法时,使用 this.thing.在您的情况下,这将是 this.strSlug(this.shop.name).

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

这篇关于如何从 vue.js 上的数据调用方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆