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

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 + "https://stackoverflow.com/" + strSlug(this.shop.name)
          },
          {
            title: 'info',
            url: '/store/' + this.shop.id + "https://stackoverflow.com/" + 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?

If you have a function in data that will be used in a context of another object (like an event handler, for example), then this will not point to the Vue instance. You will have to preserve the reference in another variable from the scope of data():

methods: {
    shuffle() {}
},
data() {
    var self = this;
    return {
        onClick: function() {
            self.shuffle()
        }
    }
}

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


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Similar Posts