Issues encountered when utilizing a computed property in Typescript to organize an array

Attempting to implement Vue in a typescript single page application, I encountered a challenge where arrays needed to be displayed on screen in sorted lists. Despite the seemingly simple nature of the problem, none of the examples I came across seemed to work with Typescript. Can someone provide a functional example of how to make Typescript accept a Vue computed function from an array within the Vue data?

I have created an orderedRegions computed function in the Vue configuration. This function is designed to return a sorted version of the "Regions" data object in Vue. The goal is for orderedRegions to output the same list but sorted alphabetically.

    computed: {
      orderedRegions: function () : Region[] {
        function compare(x : Region, y: Region) {
          if (x.name < y.name) {
            return -1;
          }
          if (x.name > y.name) {
            return 1;
          }
          return 0;
        }
        return this.Regions.sort(compare);
      }
    }

I discovered that when I remove the Typescript elements and insert this code into my compiled javascript file, it does work as intended. However, Typescript fails to compile because the "this.Regions" object is viewed as a non-existent error. It seems that Visual Studio Code expects "this" to refer to the function scope rather than the Vue scope.

Any suggestions on how to satisfy Typescript with this setup?

...additional attempts based on feedback: 1) I attempted using "shorthand" as shown below, but encountered the same issue. "This" refers to the function instead of Vue, resulting in the Typescript error: "Property 'Regions' does not exist on type '{ sortedRegions: () => any; orderedRegions(): Region[]; }"

orderedRegions() : Region[] {
    function compare(x : Region, y: Region) {
        if (x.name < y.name) {
            return -1;
        }
            if (x.name > y.name) {
            return 1;
        }
            return 0;
        }
        return this.Regions.sort(compare);
    }

2) I also experimented with the arrow function, yet faced the same discrepancy in Typescript:

orderedRegions: () => {
    function compare(x : Region, y: Region) {
        if (x.name < y.name) {
            return -1;
        }
            if (x.name > y.name) {
            return 1;
        }
            return 0;
    }
    return this.Regions.sort(compare);
}

Answer №1

For my TypeScript project, I prefer using a class-based API approach. By utilizing a class based API, it allows for the implementation of a get function to order the list accordingly. The getter is recognized as a computed function.

<template>
    <div>
        <div v-for="item of orderedList" :key="item" xs3>{{ item }}</div>
    </div>
</template>

<script lang="ts">
/** NOTE: This component bears close resemblance to the all orders component
 * It could potentially be merged with that component in the future */
import { Component, Vue, Watch } from "vue-property-decorator";
@Component
export default class List extends Vue {
    private unorderedList = ["zTest", "fTest", "aTest", "gTest"];

    get orderedList() {
        return this.unorderedList.sort();
    }
}
</script>

Answer №2

If you pass the regions to the orderedRegions function, you can avoid encountering the issue with this within the function itself.

orderedRegions(myRegions: Region[]) : Region[] {
    function compare(x : Region, y: Region) {
        if (x.name < y.name) {
            return -1;
        }
        if (x.name > y.name) {
            return 1;
        }
        return 0;
    }
    return myRegions.sort(compare);
}

I have tested this approach and it functions correctly. Interestingly, I utilized your sorting logic as well.

This method is advantageous for testing purposes as it eliminates concerns related to the this context.

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

What is the correct way to construct this query?

I've been attempting to run this query with Sequelize but keep encountering an error Query LineItem.findAll( { attributes: [ "orderId", [fn("sum", col("quantity")), &qu ...

Transferring environment variables from Azure pipelines to a Vue application using Quasar 2.6 with a readonlyrootfilesystem configuration

I am currently working on a Vue App that is powered by Quasar 2.6. I recently made a configuration change in my AWS task definition to set readonlyrootfilesystem to true. However, I encountered a problem when trying to write environment variables to a file ...

Exploring ways to utilize array.find by comparing it to a different object

There are two arrays in JavaScript named designs and articles. var designs = [ { design_id:"bwbmbqlujurv", article_id:14782, name:"adidas demogorgon black" }, { design_id:"lg9yba2gkcwr", article_id:14782, name:"harry potter w ...

In vuex, dynamic modules share common data and do not have unique data

Currently, I am facing an issue with an asynchronous API call that returns an array of objects. After receiving this data, I map it to dynamically registered modules in my store. The process looks something like this: dispatch // prior to this dispatch, ...

Guide to setting up routes in nuxt.js

I am building a blog website with Nuxt.Js on the domain xyz.com. I would like to display different pages based on country code, such as xyz.com/en/home and xyz.com/en/about. Can someone guide me on how to define routes in Nuxt.js for displaying blog conte ...

What is the best way to organize the Firebase data that is stored under the user's unique

Hey there, I'm currently working on developing a leaderboard feature for an app. The idea is that users will be able to store their "points" in a Firebase database, linked to their unique user ID. This is how the data is structured in JSON format: ...

What is the correct way to submit a formarray in an angular application following the specified format?

When submitting a form in Angular, I'm facing an issue where only the data from the first index inside the role menu is being passed. How can I ensure that all index data is passed on submit? { "roleMenu":[{ "menu":{ "menuId": 1 }, ...

How can you swap out a forward slash in vue.js?

I am facing a coding issue that I need help with: <template slot="popover"> <img :src="'img/articles/' + item.id + '_1.jpg'"> </template> Some of the numbers in my item.id contain slashes, leadin ...

What is the method for retrieving a JSON type object property that is stored inside a data object in a Vue template?

I am facing an issue with retrieving data from a Vue.js app object. data() { return { group1: { id: 'qd4TTgajyDexFAZ5RKFP', owners: { john: {age: 32, gender: 'man'}, mary: {age: 34, gender: 'wom ...

How does VueJS compare to Angular Service functionality?

I am looking to consolidate all my server communication functions and data fetching utilities into a single reusable file within VueJS. Plugins don't seem like the ideal solution. Perhaps I should consider template-less components instead? ...

Making changes to the retrieved properties using Apollo GraphQL within a Vue.js environment

I'm trying to utilize the Moment javascript library to format a date that I retrieve through Apollo-GraphQL. My setup involves VueJS Apollo on the client side for executing graphQL queries like this: import { ALL_EVENTS } from '../constants/grap ...

Conflict in Vue.js between using the v-html directive and a function

Below is the component template for a notification: <template> <div> <li class="g-line-height-1_2"> <router-link :to="linkFromNotification(item)" @click.native="readNotification(item)" v-html="item. ...

Convert the Date FR and Date US formats to ISO date format

There is a function in my code that accepts dates in different formats. It can handle two formats: 2022-06-04 or 04/06/2022 I want all dates to be in the format: 2022-06-04 For instance: public getMaxduration(data: object[]): number { data.forEach((l ...

Material Design Autocomplete search feature in Angular 2

I'm encountering some challenges with autocomplete in Angular2 Material Design. Here are the issues I'm facing: 1. When I type a character that matches what I'm searching for, it doesn't display in the autocomplete dropdown as shown in ...

Error: When trying to access the 'details' property of an undefined element within a foreach loop in Vue.js, a TypeError occurs

While working in a foreach loop, I'm attempting to assign a value using this particular operator. $.each(this.form.details,(key,value)=>{ $.each(this.form.details,(key1,value1)=>{ this.form.details[key].total=76776; }); }); form: ...

Automate the process of replacing imports in Jest automatically

Currently, I am in the process of setting up a testbench for a more intricate application. One challenge we are facing is that our app needs to call backend code which must be mocked to ensure the testbench runs efficiently. To address this issue, we utili ...

Creating a Vue equation that utilizes props to dynamically assign a class

I am trying to dynamically apply a class to a data table based on the data being passed to it. Although I can successfully run the equation in the template, I'm having trouble figuring out how to do so within the bound class. Let me show you what my ...

Creating a model and assigning values in TypeScript

I am currently developing an angular application and need to send data to a post API. The JSON structure I am working with is as follows: { "name": "julie", "id": 1, "PersonalDetails": { "hom ...

Slim API receives a request from Ionic 5

Seeking assistance with making a GET request from my Ionic application to an API constructed using the Slim Framework. Below is the code snippet of the API: <?php header('Access-Control-Allow-Origin: *'); header('Content-Type: applicati ...

Restrict Type of Child Element in Vue.js

After exploring various options, I have yet to find a definitive answer on whether this functionality can be achieved using vue.js. Coming from a react background where a similar concept exists, I am interested in implementing... My goal is to restrict th ...