Blackball Software

View Original

How to easily bind VueJS to a Typescript or ES6 class

Like many, I have been very impressed with the work done on VueJS and TypeScript and naturally I want to leverage the benefits of each in my projects.  Unfortunately the Vue configuration model does not facilitate binding to a class as such.  Instead Vue asks for a bag of methods & properties via its constructor:

See this content in the original post

But this is not the way modern Javascript applications are written:

  • Javascript components are encapsulated in classes – now supported natively in ES6 and of course in Typescript
  • Regardless of how you build your components, they should be agnostic towards any UI binding (if any) being employed against them

So, for example, the above component would be encapsulated in the following Typescript module:

See this content in the original post

It would be nice if Vue let you do something like:

See this content in the original post

…but of course it doesn’t, and hence why you are reading this post.  Well, we had this problem but with a little determination we wrote this method which maps any class into a Vue instance.  We’ve been using for a few months now and haven’t noticed any departures from normal Vue behaviours.  I’ve self-documented inline below.  Please grab and use/modify as you wish:

See this content in the original post