2.0.0 • Published 6 years ago

gent-vue v2.0.0

Weekly downloads
3
License
MIT
Repository
github
Last release
6 years ago

gent-vue

A Vue plugin to use with gent-store and rxjs

安装

npm i gent-vue gent-store -S
import {VuePlugin} from 'gent-vue';

绑定插件

import Vue from 'vue';
import {VuePlugin} from 'gent-vue';

Vue.use(VuePlugin, {
  storeOptionKey: 'store',
  storeKey: '$store',
  stateKey: '$state',
  subscriptionsKey: '$subs',

  // 为 true 时能够通过Vue.js devtools调试状态值
  debugState: process.env.NODE_ENV === 'development'
});

定义store

在根组件绑定store

在根组件上绑定后,每个组件中会有异性几个属性, 这些属性的名字都可以在使用插件的时候自定义。

  • vm.$store: Store实例。
  • vm.$state: 响应式的state,关联到store.state.
  • vm.$subs: 用来绑定订阅,组件内新建订阅的时候最好绑定在这上面,组件离开时会取消这些订阅.

    (例:vm.$subs.addUser = Observable.of(1).subscribe(item => {}))。

  • vm.$unsubscribe(key): 取消一个绑定在vm.$subs上的订阅,不传key则取消所有订阅。

import store from '../data/stores/main';

new Vue({
  store,
  mounted() {
    //
  },
  computed: {
    user() {
      return this.$sotre.state.user;
    }
  }
})

使用

获取数据: 一般直接从vm.$state获取,或者通过计算属性获取。

export default {
  computed: {
    user() {
      return this.$store.state.user;
    }
  },
  mounted() {
    console.log(this.$store.state.user)
  }
};

数据变换: 每一次数据变换开始一个数据流。

import { of, from } from 'rxjs';

export default {
  methods: {
    addItem() {
      // 放弃上次订阅,如果有
      this.$unsubscribe('addItem');

      let user = {
        id: Date.now(),
        name: 'user-' + Math.round(Math.random() * 1000000),
      };

      // 定义流
      let observable = of(user);
      // 服务器请求
      observable = observable.pipe(
        switchMap(v => {
          from(API.userAdd(v)); // 将promise转为observable
        })
      );
      // 提交store变更
      observable = observable.pipe(
        map(user => {
          this.$store.commit('user.add', user);
        })
      )

      // 订阅,开始一个数据流
      NProgress.start();
      this.$subs.addItem = observable.subscribe(
        (data) => {
          console.log('success');
          NProgress.done();
        },
        (err) => {
          console.log(err);
          NProgress.done();
        }
      );
    }
  }
};

注意

  • 不能直接更改state,所有store的更改应该通过store.commit操作。
  • 如果要把store的一些值初始化为data,可以用store.copy
data () {
  const store = this.$store;

  return {
    user: store.copy(store)
  }
}
2.0.0

6 years ago

1.0.7

6 years ago

1.0.6

6 years ago

1.0.5

6 years ago

1.0.4

6 years ago

1.0.3

6 years ago

1.0.2

6 years ago

1.0.1

6 years ago

1.0.0

6 years ago