DEV Community

狼族小狈
狼族小狈

Posted on

2 1

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

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay