In the development process of VuejS-related projects, we often use VUEX as a state management tool, and the state of the whole component as a one-way data flow mode management.

In fact, VUEX is quite complicated in practical use. Every time the demand increases, it is necessary to add upgrading-type, Action and Mutations. In order to simplify this operation, we can combine Mutations and Action and simplify the process as follows:

Under the guidance of this idea, muse-Model was born to complete the state management of the whole project in a simple and elegant way.

What is a Muse – model

Muse-model is not a new state management tool. It is developed based on VUEX, which can be said to be an auxiliary tool of VUEX. In the process of using Muse-Model, all VUEX apis are available, which also makes it convenient for vuex users to carry out transition. The store object is also passed in to initialize muse-Model.

// model.js
import Vue from 'vue';
import Vuex from 'vuex';
import MuseModel from 'muse-model';
export const store = Vuex.Store({
  strict: true
});
export default new MuseModel(store);Copy the code

use

We will use a counter example to demonstrate the use of muse-Model.

Define a Model

Model consists of namespace, State and Action

// count.js
export default {
    namespace: 'demo',
    state: {
        count: 1
    },
    add () {
        return {
            count: this.state.count + 1
        }
    },
    sub () {
        return {
            count: this.state.count - 1
        }
    }
}Copy the code

Instead of changing the state directly in the action, return the new state to be changed.

Connected components

The connect method lets you mix model into computed and methods for your component.

<template>
<div>
    <button @click="add">+</button>
    {{count}}
    <button @click="sub">-</button>
</div>
</template>
<script>
import model from './model';
import CountModel from './count';
const CountUI = {
    name: 'count-ui'
};
export default model.connect(CountUI, CountModel);
</script>Copy the code

Deal with asynchronous

All you need to do with asynchronous processing is return a Promise object.

export default { //.... Return new Promise((resolve, reject) => {setTimeout(() => {resolve({count: this.state.count + 1 }); }, 1000); }); }}Copy the code

resources

Muse-model address: github.com/myronliu347…