Skip to content

typescript-cheatsheets/vue

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

23 Commits
 
 
 
 
 
 

Repository files navigation

Vue+TypeScript Cheatsheets

Cheatsheets for experienced Vue developers getting started with TypeScript.

Section 1: Setup

Prerequisites

  1. A good understanding of Vue.js
  2. Read the TypeScript support section in the Vue docs 2.x | 3.x

Vue + TypeScript Starter Kits

  1. Using the Vue CLI , you can select the TypeScript plugin to be setup in a new a Vue project.
# 1. Install Vue CLI, if it's not already installed
npm install --global @vue/cli

# 2. Create a new project, then choose the "Manually select features" option
vue create <my-project-name>
  1. Vite is a new build tool by Evan You. It currently only works with Vue 3.x but supports TypeScript out-of-the-box.

⚠ Currently in beta. Do not use in production.

npm init vite-app <project-name>
cd <project-name>
npm install
npm run dev

Section 2: Getting Started

Recommended ts.config setup

note: strict:true stricter inference for data properties on this. If you do not use it, this will always be treated as any

// tsconfig.json
{
    "compilerOptions": {
        "target": "esnext",
        "module": "esnext",
        "strict": true,
        "moduleResolution": "node"
    }
}

Usage in .vue files

Add lang="ts" to the script tag to declare TS as the lang used.

<script lang='ts'>...</script>

In Vue 2.x you need to define components with Vue.component or Vue.extend:

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

export default Vue.extend({

  // type inference enabled
  name: "HelloWorld",
  props: {
    msg: String
  }
});
</script>

In Vue 3.x you can use defineComponent to get type inference in Vue component options

import { defineComponent } from 'vue';

const Component = defineComponent({
    // type inference enabled
});

Class Components

Vue Class Components offers an alternative class-style syntax for Vue components which integrates well with TypeScript.

To have consistent support for decorators in your Vue components, it's also recommended to install vue-property-decorator.

To get started with both libraries in your existing Vue project, run:

npm install vue-class-component vue-property-decorator

You only need to import vue-property-decorator into your .vue file as it extends vue-class-component.

You can now write TS in your components like this:

<template>
  <div>
    {{ count }}
    <button v-on:click="increment">+</button>
    <button v-on:click="decrement">-</button>
    {{ computedValue }}
  </div>
</template>

<script lang="ts">
import { Vue, Component } from "vue-property-decorator";

@Component
export default class Hello extends Vue {

  count: number = 0
  vue: string = "vue"
  ts: string = "ts"

  // Lifecycle methods can be accessed like this
  mounted() {
    console.log('component mounted')
  }

  // Method are component methods
  increment(): void {
    this.count++
  }

  decrement(): void {
    this.count--
  }

  // Computed values are getters
  get computedValue(): string {
    return `${vue} and ${ts} rocks!`
  }
}
</script>

See the full guide for Vue Class Components.

Class components should not confused with the now abandoned Class API proposal.

Props

PropType can be used to annotate props with a particular object shape.

import Vue, { PropType } from 'vue'

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

interface PersonInfo { 
  firstName: string,
  surname: string,
  age: number
}

export default Vue.extend({
  
  name: "InfoCard",
  props: {
    info: {
      type: Object as PropType<PersonInfo>,
      required: true
    }
  }
});
</script>

With vue-class-components and vue-property-decorator, you can use the Prop decorator:

<script lang="ts">
import { Vue, Component, Prop } from "vue-property-decorator";

interface PersonInfo { 
  firstName: string,
  surname: string,
  age: number
}

@Component
export default class InfoCard extends Vue {
  @Prop({ required: true }) readonly info: PersonInfo;
}
</script>

Data Properties

You can enforce types on Vue data properties by annotating the return data object:

interface Post {
  title: string;
  contents: string;
  likes: number;
}

export default Vue.extend({
  data(): { newPost: Post } {
    return {
      newPost: {
        title: "",
        contents: "",
        likes: 0
      }
    };
  }
});

It might be tempting to annotate your Vue data properties using as like this:

interface Post {
  title: string;
  contents: string;
  likes: number;
}

export default Vue.extend({
  data() {
    return {
      newPost: {
        title: "",
        contents: "",
        likes: 0
      } as Post // ❌ Avoid doing this
    };
  }
});

Note that type assertion like this does not provide any type safety. If for example, the contents property was missing in newPost, TypeScript would not catch this error.

Other Vue + TypeScript resources

About

Cheatsheets for experienced Vue developers getting started with TypeScript

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 3

  •  
  •  
  •  
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy