Skip to content

Instantly share code, notes, and snippets.

@jbenner-radham
Last active May 21, 2018 22:30
Show Gist options
  • Select an option

  • Save jbenner-radham/3ba184891e1b4119bcd2914386e1959e to your computer and use it in GitHub Desktop.

Select an option

Save jbenner-radham/3ba184891e1b4119bcd2914386e1959e to your computer and use it in GitHub Desktop.

Vue.js TypeScript Variants

Vue Extend Variant

import * as _ from 'underscore.string';
import Vue from 'vue';
import AwesomeMixin from './mixins/AwesomeMixin';
import HelloWorld from './components/HelloWorld.vue';

export default Vue.extend({
    name: 'app',
    components: {
        HelloWorld
    },
    filters: {
        title(value: string): string {
            return _.titleize(value);
        }
    },
    mixins: [
        AwesomeMixin
    ],
    props: {
        runtimeConfig: {
            type: String,
            default: '!!!'
        }
    },
    data: {
        instanceConfig: '---'
    },
    computed: {
        runtimeProperty(): string {
            return this.instanceConfig;
        }
    },
    watch: {
        instanceConfig(value: string): void {
            console.info(value);
        }
    }
});

Caveats

The data properties cannot have inline type declaration.

Class-Style Component Variant

import * as _ from 'underscore.string';
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import AwesomeMixin from './mixins/AwesomeMixin';
import HelloWorld from './components/HelloWorld.vue';

@Component({
    components: {
        HelloWorld
    },
    filters: {
        title(value: string): string {
            return _.titleize(value);
        }
    },
    mixins: [
        AwesomeMixin
    ]
})
export default class App extends Vue {
    @Prop({ default: '!!!' })
    public runtimeConfig!: string;

    public instanceConfig: string = '---';

    public get runtimeProperty(): string {
        return this.instanceConfig;
    }

    @Watch('instanceConfig')
    onInstanceConfigChanged(value: string): void {
        console.info(value);
    }
}

Caveats

undefined will not be reactive

To take consistency between the decorator behavior of Babel and TypeScript, vue-class-component does not make a property reactive if it has undefined as initial value. You should use null as initial value or use data hook to initialize undefined property instead.

From: https://github.com/vuejs/vue-class-component#undefined-will-not-be-reactive

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment