Kaijun / movue

Mobx integration for Vue.js.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Movue npm version Build Status Coverage Status License

Mobx integration for Vue.js, inspired by vue-rx.

Install

npm i movue --save

If you use yarn,

yarn add movue

Usage

Import Movue in your project and use it in Vue:

import Vue from 'vue'
import Movue from '../src'
import * as mobx from 'mobx'

Vue.use(Movue, mobx)

You can pass the min parts of Mobx to reduce bundle size:

import { reaction } from 'mobx'

Vue.use(Movue, { reaction })

Now you can use Mobx store in your Vue component:

const todoStore = observable({
  todos: [],
  get unfinishedTodos() {/* ... */},
  addTodo: action(function() {/* ... */}),
  toggleTodo: action(function() {/* ... */})
})

export default {
  data() {/* ... */},
  computed: {/* ... */},
  // you should only use data from mobx store in `fromMobx` fields
  fromMobx: {
    unfinishedTodos() {
      return todoStore.unfinishedTodos
    }
  },
  methods: {
    toggleTodo(...args) {
      todoStore.toggleTodo(...args)
    }
  }
}

Fields defined in fromMobx can be used in the template or other parts of viewModel just like normal computed fields:

<template>
  <p>Count of unfinished todos: {{unfinishedTodos.length}}</p>
</template>

You can use helper methods to simplify your code:

import { mapFields, mapMethods } from 'movue'
export default {
  data() {/* ... */},
  computed: {/* ... */},
  fromMobx: mapFields(todoStore, ['todos', 'unfinishedTodos']),
  methods: {
    // `...` requires object spread syntax support
    ...mapMethods(todoStore, ['addTodo', 'toggleTodo']),
    someOtherMethod() {/* ... */}
  }
}

API Reference

mapFields(store: object, fieldNames: string[]): Object

mapFields do fields' map for you:

const fields = mapFields(todoStore, ['todos', 'unfinishedTodos'])
// equals
const fields = {
  todos() { return todoStore.todos },
  unfinishedTodos() { return todoStore.unfinishedTodos }
}
mapMethods(store: object, methodNames: string[]): Object

mapMethods do methods' map for you:

const methods = mapMethods(todoStore, ['addTodo', 'toggleTodo'])
// equals
const methods = {
  addTodo: todoStore.addTodo.bind(todoStore),
  toggleTodo: todoStore.toggleTodo.bind(todoStore)
}

License

Apache-2.0

About

Mobx integration for Vue.js.

License:Apache License 2.0


Languages

Language:TypeScript 91.8%Language:JavaScript 8.2%