Submits Submits - 1 year ago 129
TypeScript Question

TypeScript and the this keyword (SharePoint Framework and Vue)

I'm working on a SharePoint Framework web part and using Vue.js.

Given this 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)
}
}
})
}
}


On that last return statement, how can I get to the
announcements
and
numOfAnnouncements
Vue data properties?

I have tried:

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 Source

Your problem is that this within the announcementsTrimmed function does not strictly refer to your class but to the context the function is called.

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

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

or shorter:

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

To learn more about that you could read for example the MDN documentation.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download