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.
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` -->
Example 1: Share states with components
Example 2: With arbitrary constructor
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>
TBD.
TBD.
MIT license.
Copyright 2020 Chiajun Wang (ibara1454).