Using TypeScript and the `this` keyword in SharePoint Framework with Vue

I'm currently developing a SharePoint Framework web part with Vue.js.

Check out this code snippet:

export default class MyWorkspaceTestWebPart extends BaseClientSideWebPart<IMyWorkspaceTestWebPartProps> {
  public uol_app;

  public render(): void {
    this.domElement.innerHTML = "some markup"

    this.uol_app = new Vue({
      el: `#vueapp-${this.context.instanceId}`,
      data: {
        announcements: [],
        numOfAnnouncements: 4
      },
      computed: {
        announcementsTrimmed: function() {
          return this.uol_app.announcements.splice(0, this.uol_app.numOfAnnouncements)
        }
      }
    })
  }
}

In the last return statement, how can I access the announcements and numOfAnnouncements properties in Vue's data?

I've attempted:

return this.uol_app.announcements.splice(0, this.uol_app.numOfAnnouncements)

return this.uol_app.data.announcements.splice(0, this.uol_app.data.numOfAnnouncements)

return this.data.announcements.splice(0, this.data.numOfAnnouncements)

return this.announcements.splice(0, this.numOfAnnouncements)

return uol_app.announcements.splice(0, this.numOfAnnouncements)

Answer №1

Your issue lies in the fact that the use of this within the announcementsTrimmed function does not specifically refer to your class, but rather to the context in which the function is invoked.

The solution is to convert it into an arrow function, which maintains the context for this:

announcementsTrimmed: () => {
  return this.uol_app.announcements.splice(0, this.uol_app.numOfAnnouncements)
}

or more succinctly:

announcementsTrimmed: () => this.uol_app.announcements.splice(0, this.uol_app.numOfAnnouncements)

To delve deeper into this concept, you may want to explore resources like the MDN documentation.

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

Utilizing a set for storing distinct values works well, but what happens when my array contains more data?

I recently discovered that using "SET" can be a solution to eliminate duplicated values in an array. While it works on simple examples, I'm facing a challenge when dealing with larger datasets and wanting this data to be integrated into my Vue model i ...

Tips for displaying a div near the cursor's location when hovering in React JS

Looking for a way to show a hidden div at cursor position when hovering on Text item1 or item2. Check out the sample GIF animation in this Link My attempt using Jquery code inside React resulted in an error: $(".text-item").mouseenter(function ( ...

"Customize the number of items displayed per page with Bootstrap Vue's perPage

I am currently working on a Vue project which you can view on codesandbox and utilizing bootstrap-vue. Within the project, there are multiple columns containing cards along with pagination: <template> <b-container> <b-row :cu ...

Issue with triggering Observable during an Angular 2 HTTP call

In my current setup using Ionic 2 with Angular 2, I have the following method implementation: private login(params: any, url: string){ var p = new Promise<JsonResult>((resolve, reject) => { let body = JSON.stringify(params); l ...

Styling text using CSS depending on the displayed text

Utilizing Awesome Tables (AT), I am extracting data from a Google Sheets document to display on a website. The HTML template in the sheets is used for formatting the data, specifically focusing on the table output with inline CSS styling. Since the templat ...

Attempting to send arguments to a jQuery ajax request

After successfully implementing my original ajax call, I decided to create a reusable function for it. This way, I can easily modify the data and URL fields of the ajax call without having to retype everything each time. However, I encountered an issue whe ...

Navigating through intricate JavaScript objects

I am working with an object that looks like this: var obj = { "00a9": ["\u00A9", ["copyright"]], "00ae": ["\u00AE", ["registered"]], "203c": ["\u203C" ...

Encountering syntax errors in GraphQL

Currently, I am in the process of working on the GraphQL Node tutorial and have reached step 7. Visit this link to view Step 7 While implementing the code in my datamodel.prisma file, I encountered several syntax errors: directive @id on FIELD_DEFINITIO ...

Vue warning: Additional non-props attribute (id) detected in component, unable to be automatically inherited due to component rendering fragment

While learning VUE.JS, I encountered two errors when attempting to retrieve data values for implementing Edit/Update functionality. Although I successfully retrieved all the data, I received warnings: [Vue warn]: Extraneous non-emits event listeners (edite ...

Issues with visuals in jQuery.animate

I have nearly finished implementing a slide down drawer using jQuery. The functionality I am working on involves expanding the drawer downwards to reveal its content when the handle labeled "show" is clicked, and then sliding the drawer back up when the ha ...

What are the signs that an element was visible on screen prior to navigation?

Recently, I incorporated SlideUp and SlideDown jquery animations into my website. You can check it out by visiting (click the >>>). However, I noticed a small issue where when users navigate to a new page, they have to re-SlideUp the element that was sl ...

Is there a way to check for invalid string literals within a string?

Looking for a way to test for invalid (unclosed) strings within a given string? This regex might help: /"[^"\\]*(?:\\[\S\s][^"\\]*)*"|'[^'\\]*(?:\\[\S\s][^'\\]* ...

Having trouble getting ng-click to function properly in TypeScript

I've been struggling to execute a function within a click function on my HTML page. I have added all the TypeScript definition files from NuGet, but something seems to be going wrong as my Click Function is not functioning properly. Strangely, there a ...

Revamping the Look: Refreshing Background of Div

I'm attempting to change the background image of the body element on a webpage when I hover over links with data-* attributes. It's working perfectly, but I can't seem to figure out how to create a smooth fade between the images when a link ...

Strange Scrolling Issues in Blackberry Webworks when Using Touchscreens

Within my Blackberry Webworks app designed for Smartphones OS 6, 7, and 7.1, there is a portion of code that looks like this: <div style="width:100%; height:100%; overflow:hidden;"> <div style="overflow:auto;height:100px;width:100%;"> ...

Call a PHP function within a functions file using a JavaScript function

Seeking a way to navigate between PHP and JavaScript worlds with confidence. There's a collection of PHP functions stored neatly in custom_functions.php waiting to be called from JavaScript. As I delve into the realm of JavaScript and jQuery, my fam ...

Utilizing Freebase Suggest, is there a way to refine a field by the choice of another field?

When utilizing Freebase Suggest (), and having a field that chooses between Country or State, how can I make another "City" field filter to only display cities within that selected Country or State? In addition, if a user selects "New York" as their State ...

How can I prevent the enter key from working with Twitter Typeahead?

Is there a way to prevent the enter key from being pressed on an element within Twitter Typeahead's dropdown feature while using Angular with Typescript? I attempted to utilize preventDefault() when event.keycode === 13 on the ng-keydown event for th ...

A sleek CSS text link for a stylish video carousel

I am attempting to create a CSS-only text link to video slider within our Umbraco CMS. Due to the limitations of TinyMCE WYSIWYG, I am restricted in the amount of code I can use as it will strip out most of it. So far, I have developed a basic CSS slider ...

Find the item in the pop-up window

When removing a user from my list, a JavaScript popup pops up prompting to confirm the action with two buttons "OK" / "Annuler" : Is there a way to use Selenium to find and interact with these buttons? ...