DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

η‹Όζ—ε°η‹ˆ
η‹Όζ—ε°η‹ˆ

Posted on

Use class to write setup, and support vue2 and vue3

vue-class-setup

Use class to write setup, and support vue2 and vue3

Only 1.34 KiB after gzip compression

Install

npm install vue-class-setup
# or
yarn add vue-class-setup
Enter fullscreen mode Exit fullscreen mode

Usage

<template>
    <p>{{ count.text }}</p>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import { Setup, Hook } from 'vue-class-setup';

@Setup
class Count {
    public value = 0;
    public get text() {
        return String(this.value);
    }
    @Hook('mounted')
    public init() {
        this.value++;
    }
}

export default defineComponent({
    setup() {
        return {
            count: new Count()
        }
    }
})
</script>
Enter fullscreen mode Exit fullscreen mode

Computed

Using the get accessor or computed hook, it will be converted to computed

import { Setup, Hook } from 'vue-class-setup';

@Setup
class Count {
    public get time() {
        return Date.now();
    }
    @Hook('computed')
    public getTime() {
        return Date.now();
    }
}
Enter fullscreen mode Exit fullscreen mode

Custom setup

import { Setup, Hook } from 'vue-class-setup';

@Setup
class Count {
    @Hook('setup')
    public setup() {
        // Your code
    }
}
Enter fullscreen mode Exit fullscreen mode

How to use watch?

Watch parameters are complex, so decorators are not supported, but setup hooks are provided

import { watch } from 'vue';
import { Setup, Hook } from 'vue-class-setup';

@Setup
class Count {
    public value = 0;
    @Hook('setup')
    public setup() {
        watch(() => this.value, (value) => {
            // Your code
        })
    }
}
Enter fullscreen mode Exit fullscreen mode

github

Top comments (0)

Now it's your turn.

Β 
Join DEV and share your story.