What is the best way to retrieve props for computed properties using Vue with Typescript?

Seeking help on accessing props data for my computed property. Here is the code snippet:

<script lang="ts">
import { defineComponent } from 'vue'

export default defineComponent({
  props: {
    color: String,
    shape: String,
  },
  computed: {
    theme(): string {
      const args: string[] = props.color.split('-') //Encountering error: Cannot find name 'props'
      let var_1:string = args[0]

      return var_1
    }  
  }
})
</script>

I have also tried using "this.color" but it didn't work either.

Answer №1

Utilizing this to access is the correct approach, however, Typescript raises an error because this.color could potentially be undefined. To resolve this issue, you can either make the property required or adjust your computed theme function to handle undefined values.

Take a look at the code with a required color:

<script lang="ts">
import { defineComponent } from 'vue'

export default defineComponent({
  props: {
    color: {required: true, type: String}, // <--- specify color as required
    shape: String,
  },
  computed: {
    theme(): string {
      const args: string[] = this.color.split('-') // <--- accessing using `this`
      let var_1:string = args[0]

      return var_1
    }  
  }
})
</script>

Alternatively, you can handle undefined values by doing something like this:

    theme(): string {
      return this.color?.split('-')[0] ?? ''
    } 

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

Having trouble integrating vue-phone-number-input into my VueJS Ionic project

I'm currently integrating vue-phone-number-input into my project. I successfully installed the package using npm install vue-phone-number-input. This is what my main.js looks like : // Code .... import VuePhoneNumberInput from 'vue-phone-number- ...

Error thrown when attempting to pass additional argument through Thunk Middleware in Redux Toolkit using TypeScript

I have a question regarding customizing the Middleware provided by Redux Toolkit to include an extra argument. This additional argument is an instance of a Repository. During store configuration, I append this additional argument: export const store = con ...

The TypeError encountered when using vue.js push arises from attempting to access the 'name' property of an undefined value

Here is a code snippet I am working with: new Vue({ el: '#core', data: { checkedThemes: [] ... } }) Afterwards, I have the following code: mounted() { ... var theme = parseInt(parameters['theme&apo ...

Troubleshooting a vee-validate error for a field that does not actually exist, showing up

Whenever I attempt to validate my fields using VeeValidate, an error message appears. The error only shows up after submitting the form and successfully sending data. I'm in need of some assistance, can anyone help me with this issue? vee-validate.e ...

Having trouble accessing specific results using Firestore's multiple orderBy (composite index) feature

I am facing an issue with a query that I run on various data types. Recently, one of the collections stopped returning results after I included orderBy clauses. getEntitiesOfType(entityType: EntityType): Observable<StructuralEntity[]> { const col ...

**Finding the Index of a Table Row in Vue-Tables-2**

Recently, I came across some vue code that utilizes vue-tables-2. The table in question is quite simple and looks like this... <v-client-table :data="myRows" :columns="columns" :options="options"> <div slot=" ...

a tutorial on linking component data to a prop value

Is there a way to connect the searchString value in my Vue component to the item value in the html template it uses? I need to pass this value to the method called in my Ajax request. Vue: Vue.component('user-container-component', { props: ...

The Electron/React/Typescript module is missing: Error: Unable to locate 'fs' in the /node_modules/electron directory

Within my Electron application, I have a file named App.ts. It contains the following code snippet: import { ipcRenderer } from 'electron'; // remaining code However, during the app development process, I encountered this error message: Error: ...

Array[object..] logical operators

I am currently working with Boolean and logical operators using code like this: Just so you know, I want to convert object values and logic into an array to perform logical operations. For example: object1.logic object.operators object2.logic as either tr ...

Ways to activate a watcher even when it is assigned to the same newVal

Currently, I am utilizing the vue3 framework with the options api You can refer to the demonstration provided in the following stackbiltz link here In my setup, there is a child-component that features a button. Upon clicking this button, the refresh met ...

Tips for integrating Tesseract with Angular 2 and above

I'm currently exploring the use of Tesseract within one of my components for OCR processing on a file. .ts: import * as Tesseract from 'tesseract.js'; fileToUpload: File = null; handleFileInput(files: FileList) { this.fileToUpload = f ...

Efficient Ways to Store Text and Images in Vue.js

I have developed a tool that enables users to upload an image and overlay custom text on it, which can be viewed and edited in the browser. My query is whether it is feasible to save the combined image and text as separate files (e.g., jpg/png) using VueJS ...

Utilizing Nicknames in a JavaScript Function

I'm dealing with a function that is responsible for constructing URLs using relative paths like ../../assets/images/content/recipe/. My goal is to replace the ../../assets/images section with a Vite alias, but I'm facing some challenges. Let me ...

Employ a data or computed property that relies on the value of the prop. The prop will be changed

I'm trying to open a modal in Vue, but I keep getting this error message in the console from the navigator: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed ...

A guide on sending arrays from javascript to a Laravel controller through axios

Currently, I am utilizing Laravel 5.4 and Vue 2 to manage my data. I am facing an issue where I need to call a controller method using axios while passing two arrays. These arrays are crucial for making database requests in the controller and retrieving ne ...

Uploading multiple files simultaneously in React

I am facing an issue with my React app where I am trying to upload multiple images using the provided code. The problem arises when console.log(e) displays a Progress Event object with all its values, but my state remains at default values of null, 0, and ...

The "users" property or method has not been defined in Vue.js applications

During the development of my Vue.js shopping cart, I encountered an issue where I wanted to display the username in a label after the user provided correct information. However, I received the following error in Google Chrome: vue.js:634 [Vue warn]: Prope ...

Encountering a Typescript error while trying to implement a custom palette color with the Chip component in Material-UI

I have created a unique theme where I included my own custom colors in the palette. I was expecting the color prop to work with a custom color. I tested it with the Button component and it performed as expected. However, when I attempted the same with the ...

Difficulty with conflicting styles when dynamically loading components in Nuxt3

I'm facing a challenge with my Nuxt 3 application where I need to dynamically load different Header components for Mobile and Desktop devices. I have created Header.vue and MobileHeader.vue for this purpose, and want to display them based on the dev ...

Utilizing Vuejs to bind user input to options in a dropdown menu

I'm currently encountering difficulties while developing a basic currency converter. I am struggling with binding the selected option and displaying its corresponding value in the input field. <template> <div class="mx-auto flex fl ...