Is there a way to invoke a method using data in Vue.js?

Here is my Vue component code:

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

When running the code, an error occurs as follows:

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

After console.logging(window.location.pathname), the output is:

/store/21/chelsea-hazard-store

The goal is to highlight tabs that match the current URL

To achieve this, a method called strSlug is used to convert text into kebab case

However, it seems there is an issue with calling the method from within the data section

How can I fix this error?

Answer №1

If there is a function within the data that needs to be accessed in a different context, such as an event handler, then the reference to the Vue instance will not be available through this. In order to access it, you must store the reference in another variable within the scope of the data():

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

Answer №2

Remember to always access data or methods within the vue object by using this.thing. For example, in your situation, you should use this.strSlug(this.shop.name).

Answer №3

Using 'this.' will not resolve the issue as the function is not defined during data initialization. Consider implementing it within the created() life-cycle hook.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

AngularJS allows for editing elements in an array, but not string objects directly

I am a beginner in AngularJS, currently in the learning phase. Query I want to edit a specific rma from the list. When I click on the edit button and call the controller function updateRma(rma), after selecting rma number 11, my absolute URL is "http://l ...

"Experiencing Issues with jQuery as Thumbnails Caption is Not Functioning Proper

I am currently working on creating interactive thumbnails using jQuery. However, I have encountered an issue where the caption only displays on the last thumbnail. It doesn't show up individually for each one as intended. How can I modify my code to ...

An issue with the n constructor has been encountered for the bs4.5.2 dropdown in combination with jQuery version 3.5.1

When looking at index.html, I have these scripts included: <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/@popperjs/<a href="/cdn-cgi/l/email-protectio ...

"Automatically initiate a build in Heroku for NextJs whenever there is a data

We are managing two applications on Heroku: a KeystoneJS 6 backend and a Next.js 14 frontend. Both apps have independent repositories on GitHub and are connected to Heroku using the GitHub Deployment Method. As the primary developer for backend tasks, my g ...

NodeJS performance issues related to latency

While this issue is primarily related to Nodejitsu, similar occurrences have been observed on other VPS services as well. I have a real-time game that utilizes socket.io, and at times the server will take an unusually long time to respond. When multiple re ...

Tips for showcasing a designated set of numbers in Vue Js while iterating?

Is there a way to specifically target numbers during a loop? For example, I only want to retrieve numbers 5 and above or within a certain range that I specify. <select name="" id="input" class="form-control" v-model="selectcompetitionyear"> < ...

My webpage is experiencing issues with function calls not functioning as expected

I have created a select menu that is integrated with the Google Font API. To demonstrate how it works, I have set up a working version on JSBIN which you can view here. However, when I tried to replicate the code in an HTML page, I encountered some issues ...

What is the function of `function(data){}` in the context of JQuery's $.get

Within my MySQL database, there exists a column for VideoID and VideoCode In backend.php, I have crafted a PHP function with the goal of selecting the subsequent video from the list in the following manner: $VideoID = 0; function nextvideo(){ global ...

Combining numerous objects into one object within an array, each with distinct keys, and displaying them using FlatList

I'm struggling to present this information in a FlatList. Array [ Object { "-N1gqvHXUi2LLGdtIumv": Object { "Message": "Aeaaeaea", "Message_CreatedAt": 1652167522975, "Message_by_Ema ...

Using javascript to locate and substitute a word divided among multiple tags - a step-by-step guide

I need to utilize JavaScript to locate and substitute a word that has been separated into multiple tags. For instance, consider the following HTML code: <html> <body> <div id="page-container"> This is an apple. ...

Console displaying a 400 bad request error for an HTTP PUT request

I'm currently in the process of developing a react CRUD application using Strapi as the REST API. Everything is working smoothly with the GET, DELETE, and CREATE requests, but I encounter a 400 bad request error when attempting to make a PUT request. ...

Incorporating Select2 into Your Laravel 4 Application

I've recently incorporated select2 into my multiselect search filter, but I'm struggling to integrate it effectively. Here's the method I'm using: public function getContactByName($name) { return Contact::select(array('id&apo ...

What could be causing this array to be blank?

In the process of working on a product feedback app using React for my portfolio, I encountered an unexpected issue. The problem arises in my SuggestionDetails component, where I am fetching the current id with useParams and filtering out the current produ ...

Remove elements from an array based on the indices provided in a separate array

1) Define the array a = [a,b,c,d,e,f,g,h,i,j]; using JavaScript. 2) Input an array 'b' containing 5 numbers using html tags. This will be referred to as the 'b' array. 3) Insert elements into array 'b' ensuring they are alwa ...

Unable to show information matching the marker on the infowindow in Google Maps API (v3)

I am encountering an issue with displaying amcharts in the infowindow on Google Maps. The problem is that my charts are not looping data properly within the infowindow. For example, when I click on marker 1, the data ratio does not display correctly, and w ...

Turning simple text into JSON format

Beginner JS coder here, currently developing a program that pings IoT devices on a network and outputs a true or false value based on the success of the ping. Everything is functioning well so far, but I'm now attempting to extract specific propertie ...

Implementing TypeScript type definitions for decorator middleware strategies

Node middlewares across various frameworks are something I am currently pondering. These middlewares typically enhance a request or response object by adding properties that can be utilized by subsequent registered middlewares. However, a disadvantage of ...

Can uniform columns be created in separate HTML elements?

Looking to create a uniform list in HTML, where the columns inside each panel line up perfectly. See the desired layout: https://i.sstatic.net/FbbPu.png In this example, Col_1 has a width of "BBBBB", as it is the widest content in that column, ...

How can I designate unreleased files as dynamic entries in a webpack configuration?

Here is the configuration for webpack.config.js: const CssMinimizerPlugin = require('css-minimizer-webpack-plugin'); const fs = require('fs'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const path = require(&apo ...

Avoiding the loading of textures on the obj model in three.js is essential

Can anyone assist with why the texture is not loading? I attempted to load the texture onto a separate mesh in obj file but it's not working, giving an error. Can someone explain why the material is applied but the texture is not loading? var manage ...