Attempting to feed information into a computed property within Vue.js

I'm currently working on a project that involves Vue JS, specifically Nuxt JS. Within my web page, I am required to render certain classes onto an element that exists within a v-for loop. To achieve this, I need to pass data to a computed property along with validation classes. However, I am encountering an issue where my computed property is not accepting the arguments. What could be the mistake I am making?

The error message I see is:

_vm.getClassesForDataItem is not a function

Below is the snippet of my code:

<template>
  <div>
    <ul v-for="(source, table, sourceIndex) in editor.sources" :key="sourceIndex" class="mb-3">
      <li>

        <!-- Data Source (Table) -->
        <validation-provider
          name="data source"
          :rules="{ required: { allowFalse: false } }"
          v-slot="{ errors, classes }"
        >
          <label :for="'source-'+sourceIndex" class="font-medium text-gray-700 cursor-pointer block p-4 border rounded-md ring-2" :class="getClassesForDataItem(source.isChecked, classes)">
            <div class="flex">
              <div class="flex-1">
                <p class="text-xs font-medium text-gray-400">Data Source</p>
                <h5 class="text-sm font-bold text-gray-500" :class="source.isChecked ? 'text-indigo-600' : ''">{{ table }}</h5>
              </div>
              <div v-if="source.isChecked" class="flex-1 items-center flex justify-end" :class="source.isChecked ? 'text-indigo-600' : ''">
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" height="24" width="24" viewBox="0 0 24 24" stroke="currentColor">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
              </div>
            </div>
            <input :id="'source-'+sourceIndex" v-model="source.isChecked" type="checkbox" class="focus:ring-indigo-500 h-4 w-4 text-indigo-600 border-gray-300 rounded cursor-pointer hidden">
          </label>
          <span class="text-xs text-red-500">{{ errors[0] }}</span>
        </validation-provider>

      </li>

    </ul>
  </div>
</template>

<script>
export default {
  computed: {
    getClassesForDataItem () {
      if (classes) return classes
      return ui ? 'border-indigo-300 ring-indigo-50' : 'border-gray-300 ring-gray-50'
    }
  }
}
</script>

Should I consider using a method instead of a computed property for this scenario?

Answer №1

One interesting thing about computed properties is that they cannot accept parameters. However, there is a workaround where you can actually return a function from the computed property that can take in parameters:

getClassesForDataItem() {
    return ui => ui ? 'border-indigo-300 ring-indigo-50' : 'border-gray-300 ring-gray-50';
}

If you prefer, you can also transfer this functionality to a method. Check out this link for a detailed comparison between the two approaches.

Answer №2

To enhance your computed property, consider returning a function with custom parameters:

export default {
  computed: {
    getStyledClassesForElement () {
      return (ui, errorClasses) => errorClasses || (ui ? 'border-indigo-300 ring-indigo-50' : 'border-gray-300 ring-gray-50')
    }
  }
}

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

When browserify is utilized, the error "function is not defined" may show up as an Un

Exploring an example at and attempting a function call as shown below: My HTML code is: <!DOCTYPE html> <html> <head> <title>Testing Browserify</title> <script src="bundle.js"></script> </head> <body& ...

Extract the necessary fields from the JSON Schema

I am in search of a solution to extract the required fields from a JSON Schema and Data combination. Currently, we are utilizing AJV for getting error messages in our forms using JSON Schema, and it has been performing really well. I am looking for a met ...

Enable Sound when Hovering over Video in React Next.js

I am currently facing an issue while trying to incorporate a short video within my nextjs page using the HTML tag. The video starts off muted and I want it to play sound when hovered over. Despite my best efforts, I can't seem to get it working prope ...

Using cascading style sheets to switch a page into editing mode

Is it possible to change the view of a page after clicking a button without using javascript, and instead relying solely on CSS? I want to display a page with information where users can click an edit button and make changes within the same view rather th ...

When integrating string variables into JavaScript regular expressions in Qualtrics, they seem to mysteriously vanish

I have been working on a project to analyze survey responses in Qualtrics by counting the number of matches to specific regular expressions. For example, whenever phrases like "I think...", "In my opinion," are used, the count increases by one. Below is t ...

Error in NodeJs: ReferenceError - the variable I created is not defined

Encountering an issue while attempting to use a module in my router file. I have successfully required it, but now I am seeing the following error message: ReferenceError: USERS is not defined at c:\work\nodejs\router\main.js:32 ...

Perform individual conditions (filters) sequentially within a MongoDB query

Currently, I am working on a query that involves using $and to apply multiple filters or conditions. While explaining the query, I realized that $and does not function in the same way as the JavaScript && operator. How can I simulate JavaScript && functi ...

Universal capability for selecting all items in a table

Here we have a snippet of code from my grid (CRUD) component: <template> <table class="MyComponent table"> <thead> <tr> <th width="30px"> <b-form-checkbox v-model="allC ...

Capture the Promise Rejection

During my test with WebdriverIO, I consistently encounter an issue specifically with this line of code: await browser.waitForVisible('#tx-sent li', 15000) Intermittently, a Promise rejection error occurs: Error: Promise was rejected with the ...

Creating dynamic computed properties at runtime when interacting with the Vue instance

Is there a way to programmatically create computed props while still being able to access the instance for dynamic values? For example: <script> export default { computed: { ...createDynamicPropsWithTheContext(this), // helper function that re ...

Pass Form ID To Function In A Dynamic Way

I have multiple forms on my webpage and I want to use the same ajax function for all of them. It currently works well for one form by fetching the id with getElementById and then passing it to the ajax function. My goal is to dynamically pass down the form ...

Mandate that users select from the available place autocomplete suggestions exclusively

I have integrated the "Places" Google API to enable address autocomplete in an input field on my website. However, since the service is limited to a specific area, I have implemented an autocomplete filter. The issue I'm facing is that users are stil ...

What is the best way to encode a GLTF file without compromising the encoding of other meshes and textures?

Currently, I am working on a fascinating web AR app that enables users to don GLTF head models. (You can check it out at ) To ensure optimal lighting of the GLTF model, I have implemented renderer.outputEncoding = THREE.sRGBEncoding, which has been very ef ...

The property fetchPriority is not a valid attribute for HTMLLinkElement

The HTMLLinkElement model has a property mentioned above (as shown in the image), yet the compiler is indicating that the property does not exist. Interestingly, there is one reference visible (the reference I have included in my component). https://i.sst ...

What could be causing my LESS files not to compile properly in grunt?

I've successfully installed npm and ran npm init. Additionally, I've installed the following packages using npm: grunt grunt-contrib-less grunt-contrib-watch jit-grunt --save-dev My Gruntfile.js configuration looks like this: module.exports = f ...

Tips for updating Okta token when there are changes to claims

Currently, my react app is successfully using oauth (specifically okta), but I am encountering a problem. Whenever I modify the claims in the authorization server, the changes are not reflected in the app until the token expires or I perform a logoff and ...

Exploring VueJS templating: Loading external templates

Being new to Vue.js, I have some experience with AngularJS where we used to load templates like this: template: '/sometemplate.html', controller: 'someCtrl' My question is how can we achieve something similar in Vue? Instead of embeddi ...

Conceal the scroll bar while the page preloader is active

Is there a way to hide the scroll bar while the preloader is loading on a webpage? I want to prevent users from scrolling until the preloader disappears. I have tried using CSS and setting the body overflow to hidden, but it's not working as expected. ...

Developing a website using custom modules in Node.js and Express framework

I am currently encountering an issue when using a custom module within one of my route functions in Express with node. Below is my current setup: In the app.js file, I require the module as follows: c_controller = require( './core/c_controller' ...

What is the best way to obtain root access and utilize disk usage (du) within the main process of Electron?

In the process of developing a macOS application with the help of Electron, I encountered an issue. Attempting to execute the following command from the main process using ipcMain and NodeJS's exec: // Navigating to a directory and utilizing disk us ...