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

Cypress testing with Vue: a guide to mocking API calls using actions in Vue

Could someone help me test an action involving an API call? This is the action in my Vuex store: The file containing actions in my store is 'ex.js', and it includes exActions.js export const exActions = { getExFromApi({ commit, rootGetters ...

Attempting to transfer information from a JSON file to a Netflix-inspired platform

Images I am currently working on integrating data from my json file export const products = [ { name: 'iPhone 11', image: '/assets/images (7).jpeg', time: '1 hour 14mins', age: '+16&apo ...

The beforeCreate function is failing to execute when a new user is being created

I'm currently working with sailsjs version 0.11.0. My goal is to ensure that when a new user is created, their password is encrypted before being stored in the database. To achieve this, I have implemented the use of the bcrypt library. In my User.js ...

Encountered a $resource configuration issue while making a request to the SharePoint REST service with Angular

In an old sample app without angularJS, a rest service is called in the following way: This app does not use angularJS. var listName = "Events"; // the url to use for the REST call. var url = SPAppWebUrl + "/_api/SP.AppContextSite(@target ...

Several different factors

I need to develop a form that allows users to edit existing comments. The form will display a textarea containing the old comment text and a submit button. My goal is to send the newComment data via ajax to another script. However, I am facing an issue w ...

sending data between pages in a Next.js application

I'm working on a project that consists of two pages: test1 and test2. I want to pass a prop from page 1 to page 2 without using the useRouter hook or setting it as a query string. In my test1 page, I have a color variable defined as const with a value ...

Adjust the height for just one md-tab

Looking to find a way to set the height of the content within an <md-tab> element to be 100% in a flexible manner. For example, consider the following structure: <body> <md-content> <md-tabs> <md-tab label= ...

Error 404 encountered while trying to access a website with parameters using Vue.js

Currently, I am in the process of building a website using VueJS and recently discovered how to use url parameters. Everything was working perfectly on my local machine - I could easily navigate to different pages by including parameters in the URL. For e ...

Using Node.js to download and install npm packages from the local hard drive

Is there a way to add an npm package to my Node.js project from my hard drive? It seems like the admin at work has restricted access to npm. I managed to install npm, but whenever I attempt to run "npm install express" in the command line, I keep getting ...

The call to 'setRequestHeader' on 'XMLHttpRequest' was unsuccessful due to the object's state not being OPENED

While developing an angular application with a restful API get(), I encountered a few errors such as unauthorization error:401 which I managed to resolve. However, now I am facing another error that seems quite straightforward. I even tried adding the CORS ...

Using Javascript to modify file permissions in Google Drive

I'm new to writing and seeking amazing solutions for all the issues I encounter. I have a website hosted on Google Drive, utilizing its SDK for Javascript. Everything functions exceptionally well, except for one problem. I need to adjust the permissi ...

Differences in Function Scope: A Comparison of ECMAScript 6 and ECMAScript 5

What are the advantages of ES6 compared to ES5 when it comes to block scope functions? Although the blocks may look similar in both cases, what impact does it have performance-wise and which approach is more efficient? ES6 Block { function fo ...

Preventing file visibility in Three.js resource directory

Once a user clicks on a specific 3D model, I retrieve it from the server and render it in the browser using three.js. However, there is an issue when the user tries to access a model that is not free - they can easily view and download the STL file by go ...

Multiple instances of jQuery file being loaded repeatedly

Having an issue with the jQuery file (jquery-1.11.3.min.js) loading multiple times. It seems that other jQuery files in the index.html page might be causing this. Any advice on how to resolve this would be greatly appreciated. <script type="text/javasc ...

Error: React Beautiful D&D is unable to retrieve dimensions when no reference is specified

Hey everyone! I'm currently working on a meta form creator and having some trouble with performance issues. I created a sandbox to ask for help, but keep getting the error message "Cannot get dimension when no ref is set" when trying to drag a second ...

Identify and track colored dots within an image using tracking.js

I'm working on creating a program that can tally the number of dots on dominoes in an image, such as the one shown here: My goal is to develop this functionality using JavaScript. I've attempted to learn how to utilize tracking js through variou ...

Is it possible to scroll a div on mobile without the need for jQuery plugins?

Upon investigating the initial query, we managed to implement D3js for identifying a scroll event. This allowed us to scroll the div #scroll-content from any location on desktop devices. However, we encountered an issue where this method does not function ...

Guidance on specifying a type based on an enum in Javascript

I have a list of animals in an enum that I want to use to declare specific types. For instance: enum Animals { CAT = 'cat', DOG = 'dog', } Based on this Animal enum, I wish to declare a type structure like so: type AnimalType = { ...

When using MERN Stack (with Typescript) on DigitalOcean, encountering an issue where HTML files are displayed instead of JS and

Upon checking the console, I encountered this https://i.sstatic.net/PWoT5.jpg The app has been developed using Ubuntu and Nginx so far with no firewall configuration yet in place. This is my first time deploying a MERN stack and utilizing DigitalOcean. ...

The unpredictable behavior of the `this` keyword while troubleshooting a TypeScript program in VS code

Upon further investigation, it seems that the issue I encountered was related to using Chrome for debugging my full application. This led me to question whether the problem stemmed from TypeScript or VS Code. Before submitting my findings, I decided to sw ...