Skip to content

ibara1454/vue-viewmodel

Repository files navigation

Vue-ViewModel: An Android-like ViewModel implementation for Vue 3.0

Version GitHub Actions codecov Codacy Badge License: MIT

Vue-ViewModel is a plugin for managing states over components and lifecycles, which is inspired by Android Jetpack ViewModel.

  • Scoped state management.
  • OOP-style state construction.
  • Easy to test.

Installation

Install via npm:

npm install --save vue-viewmodel

Install via Yarn:

yarn add vue-viewmodel

For prototyping, you can use the latest version via CDN:

<script src="https://unpkg.com/vue-viewmodel@latest/dist/umd/index.js"></script> <!-- Then access the plugin by the global variable `VueViewmodel` -->

Examples

Example 1: Share states with components

Example 2: With arbitrary constructor

Example 3: With DI framework

Usage

To use this plugin in your project, you have to apply the plugin to your application instance at first:

import { createApp } from 'vue'; import { plugin } from 'vue-viewmodel'; import App from './App.vue' const app = createApp(App); // Apply this plugin to your application. app.use(plugin); app.mount('#app');

And write your own ViewModel class to extends ViewModel:

// MyViewModel.ts import { ref } from 'vue'; import { ViewModel } from 'vue-viewmodel'; export default class MyViewModel extends ViewModel { count = ref(0); clear() { super.clear(); // Release your resources and listeners *HERE*. } }

Finally, you can get the ViewModel scoped by the current vue instance:

<!-- MyComponent.vue --> <template> <div>count: {{ count }}</div> </template> <script> import { defineComponent } from 'vue'; import { viewModels } from 'vue-viewmodel'; import MyViewModel from './MyViewModel.ts';  export default defineComponent({  setup() {  const viewModel = viewModels(MyViewModel);  return { count: viewModel.count };  } }); </script>

Documentation

TBD.

Contribution

TBD.

License

MIT license.

Copyright 2020 Chiajun Wang (ibara1454).

About

A plugin for managing states over components and lifecycles for Vue 3.0

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published