fastrx 1.4.3 新增 vue 扩展

受到vue-async-computed启发,为了方便在vue中使用fastrx。模仿vue-async-computed实现了一套自动订阅自动取消订阅的vue扩展:

首先需要注册扩展

import { rx } from "fastrx";
import RxComputed from "fastrx/vue";
Vue.use(RxComputed);

然后就可以在vue组件中使用: 

<template>
    <div @click="onClick1" :style="{top:y+'px',left:x+'px'}">
        <span>{{test1}}</span>
        <span>{{test0}}</span>
    </div>
</template>
<script>
import {rx} from 'fastrx'
export default {
   rxComputed:{
       test0:_this=>rx.interval(1000).take(10),//简单的订阅
       test_watch:{//使用watch触发Observable发射数据
           get:ob=>ob.switchMapTo(rx.interval(1000)).map(x=>10-x)
           watch:"test1"
       },
       test1:{//使用设置方法的方式触发,可以提供给事件回调
           get:ob=>ob.switchMap(rx.timer(1000)),
           handler:"onClick1"
       },
       test2:{
           call:true,//调用test2方法而不是设置属性
           get:ob=>ob.switchMap(e=>rx.timer(1000).map(()=>e)),
           handler:"onClick1"
       },
       "x,y":{//采用解构,将结果对象中的x,y属性分别写入vue实例中的x和y属性
            get:ob=>ob.switchMap(e=>rx.timer(1000).map(()=>({x:e.screenX,y:e.screenY}))),
           handler:"onClick1",
           default:{x:0,y:0}//设置默认值
        }
   },
   methods:{
       test2(e){
           console.log(e)
       }
   }
}
</script>

以上演示了所有功能,其中get方法中传入的ob参数本质上是一个subject,相同的handler会共用一个subject。在vue组件desctroyed的时候会全部取消订阅防止内存泄漏。

猜你喜欢

转载自www.oschina.net/news/128747/fastrx-1-4-3-released