Exploring the Vue data objects with Typescript

Recently, I made the transition from plain JavaScript to Typescript (or at least I'm attempting to). Below is code that was functioning perfectly prior to this change, with the exception of the typings added so far:

<script lang="ts">
    import axios from 'axios';

    export default {
        name: "Index",
        data() {
            return {
                years: Array,
                bgs: Array
            }
        },
        methods: {
            loadYears: function (): void {
                let self = this;
                axios.get('../letter/get/years').then(function (response) {
                    function pushYears(value: any) {
                        self.years.push(value);

                    }

                    response.data['years'].forEach(pushYears);
                });
            },
            loadBg: function (): void {
                let self = this;
                axios.get('../bg/get/all').then(function (response) {
                    JSON.parse(response.data['bgs']).forEach(function (obj: any) {
                        self.bgs.push(obj);
                    })
                });
            }
        },
        beforeMount() {
            this.loadYears();
            this.loadBg();
        }
    }
</script>

Following my switch to Typescript, I encountered issues where self.years.push(value) and self.bgs.push(obj) are no longer functional. The error message states: "self.$data.years.push is not a function". Curiously, within the beforeMount()-function, an error occurs indicating that loadYears() and loadBg are undefined, yet accessing the data()-objects functions seamlessly in this block through this.data().years or bgs. How can I access these properties within my methods-block?

Answer №1

There are two options for defining your data properties in the following way:

<script lang="ts">
import Vue from 'vue';

interface Model {
  name: string
  age: number
}

export default Vue.extend({    
  data () {
    const items: Model[] = [];
    return {
      items,
      elements: [] as Model[]
    };
  },

  mounted () {
    this.items.push({
      name: 'user', age: 22
    });
    this.elements.push({
      name: 'guest', age: 20
    });
  },
});
</script>

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 sets these async method declarations apart?

What goes on behind the scenes? const facade = { // A: doSomething: async () => await delegatedFunction(), // B: doSomething: async () => delegatedFunction(), // C: doSomething: () => delegatedFunction(), // D: do ...

What is the best way to convert the data stored in an object to an array?

I have a function that is constantly checking for temperature data: {"a":"43", "b":"43", "c":"42", "d":"43", "e":"40", "f":"41", "g":"100", "h":"42.6"} My goal is to graph this data over time, but I'm struggling with how to structure it to fit the f ...

When attempting to pre-render a Next.js page using getStaticProps(), an error occurs stating that the image is missing the required "src" attribute when using next/image

After reading the documentation for nextjs, I learned that the getStaticProps function should pre-render data that I need before a user visits my site. My goal is to fetch images and load them onto cards. In my index.js file: export async function getSta ...

Using AngularJS to add a unique custom class directive to each item in an ng-repeat loop

Can anyone help me figure out why the width of a div isn't being set dynamically using AngularJS? <ul id="contents"> <li ng-repeat="content in contents"> <div class="content_right custom_width"> <div class="title"> ...

Translating code from Java to JavaScript with the help of the G

I am facing a challenge where I need to convert Java code into JavaScript while preserving all method, variable and parameter names. Is it possible to achieve this using the GWT compiler or any other tool available in the market? I attempted compiling the ...

Production Challenges: Addressing Style Problems with Material UI and Next JS 13

Using MUI in DEV results in a custom design for my application In Prod, the custom design is missing when using MUI Do I need to implement something differently? Is there an extra configuration required? An example of something not working: <Ty ...

Play video on slick slider slide completion

Currently, I am utilizing slick slider to craft a hero block where both a Vimeo video and an image are set to automatically slide. The functionality is working as intended; however, I am looking to have the autoplay pause once the slide containing the Vime ...

Stop Wordpress from automatically preloading html5 videos

I have a WordPress page containing numerous videos and I am looking to prevent them from preloading using HTML5. The challenge is that I am inserting the videos through the featured media options, which means I cannot directly add the preload="none" attrib ...

Having trouble choosing an option from the dropdown menu in bootstrap

I'm experiencing an issue with a bootstrap dropdown that I created. I am unable to select an item from it. The code is shown below: var aos = ''; $('.dropdown-item').click(function(event) { event.preventDefault(); // Prevents ...

Tips on retrieving JSON data from javascript files

Hey everyone, I need assistance with using Tumblr and connecting my Twitter account. Tumblr provided me with this sample file: I'm wondering if it's possible to retrieve follower count and screen name data from this file. If so, can someone guid ...

Choosing multiple options from a list

I am working on a messaging app where users can compose and send messages to contacts. Currently, I am only able to send messages to one contact at a time. My goal is to enable users to select multiple contacts to create group messages. Since I am new to a ...

Developing with node and express: optimizing your workflow

After researching various blogs and tutorials on node + express development workflow, there is one crucial aspect that seems to be missing: When developing, which version of the app should you have open in your browser? The source app, featuring clean, ...

A technique for calculating the total quantity of each item individually while using v-for in VueJS

Struggling to code (complete newbie) using VueJS and facing a major roadblock. I have a list of orders and I need to sum the quantities of each item separately. The only way to access the items is through v-for. <tr> <td data-th="list"> < ...

How can I dynamically insert the highest number from a specific group of numbers in a table using JavaScript?

PROBLEM: I am currently working on a loop to insert values into a MySQL DB. Within this loop, I am generating a MAX(num) to retrieve the highest number in each selected store group. After that, the application creates a list with various values conta ...

Is it possible to launch an Electron application by clicking a run button in the VSCode

I'm new to using VSCode and am currently working on an HTML5 app with Electron. I'm finding it cumbersome to switch between windows and enter a command each time I want to test my application. Is there a way to configure VSCode to run my Electron ...

Customize the ID key in Restangular

When using Restangular, default behavior for PUT/PATCH/POST operations is to use the id of an item as the primary key. But what if you want to use a custom key like a slug or number instead? // GET to /users Users.getList().then(function(users) { var ...

What is the best way to use jQuery to place an <img> within an <a> tag?

Exploring JSON data through JavaScript, I have successfully retrieved links with the following code: (function() { var flickrAPI = "https://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?"; $.getJSON( flickrAPI, { id: "132455232 ...

Accessing the current position of skeleton bones in Three.js while an animation is playing

I currently have a Three.js project with an animated scene and I am trying to obtain the positions of skeleton bones at various points in time. If I visit, for instance, and inspect the Three.js scene: const modelViewer = document.querySelector("m ...

Decoding JSON in Angular for Model Declaration

When trying to build a model and parse JSON data, I am facing an issue with the parsing process. The structure of my JSON data is as follows: { "receiptNo": [ { "_id": "5ba6101964991b2f44e1c9cf", "receiptNo": "21471", ...

The root styles are failing to be implemented in an angular-cli project

I am currently working on a project using angular-cli and SCSS. I have noticed that while other SCSS files are successfully compiled and changes are visible, styles.css and app.component.scss in the root path remain uncompiled and their changes cannot be o ...