Vue-rx 初體驗

栏目: JavaScript · 发布时间: 6年前

内容简介:若說 Ramda 是 FP 在 ECMAScript 對於RxJS 在 Angular 2 之後已經是 framework 的標準配備,Vue 也由官方將 RxJS 6 整合進 Vue,稱為 Vue-rx。Vue 2.5.21

若說 Ramda 是 FP 在 ECMAScript 對於 同步 的解決方案,RxJS 則是 FP 在 ECMAScript 對於 非同步 的解決方案。

RxJS 在 Angular 2 之後已經是 framework 的標準配備,Vue 也由官方將 RxJS 6 整合進 Vue,稱為 Vue-rx。

Version

Vue 2.5.21

Vue-rx 6.1.0

RxJS 6.3.3

安裝 Vue-rx

$  yarn add vue-rx rxjs

雖然 Vue-rx 是 Vue 官方所維護,但目前 Vue-rx 並不像 Vuex 可透過 Vue CLI,必須自行使用 Yarn 安裝。

Vue-rx 初體驗

Vue-rx 初體驗

  1. 安裝完會發現在專案根目錄的 package.json 多了 rxjsvue-rx

Main.js

main.js

import Vue from 'vue';
import VueRx from 'vue-rx';
import App from './App.vue';

Vue.use(VueRx);
Vue.config.productionTip = false;

new Vue({
  render: h => h(App),
}).$mount('#app');

第 2 行

import VueRx from 'vue-rx';

Import vue-rx

第 5 行

Vue.use(VueRx);

讓 Vue instance 可以使用 VueRx。

Component

HelloWorld.vue

<template>
  <h1>{{ interval$ }}</h1>
</template>

<script>
import { interval } from 'rxjs';

export default {
  name: 'HelloWorld',
  subscriptions: () => ({
    interval$: interval(1000),
  }),
};
</script>

首先來看最簡單的 Vue-rx 應用。

第 6行

import { interval } from 'rxjs';

先 import RxJS 的 interval()

10 行

subscriptions: () => ({
  interval$: interval(1000),
}),

Vue-rx 提供了 subscriptions ,專門放置 Rxjs 的 Observable

其中 subscriptions 如同 datacomputed 一樣都是 function,回傳的是 object。

Observable 建議的命名方式是在名稱後面加上 $ ,其值為 RxJS 的 interval() ,每 1 秒鐘會送出新的值。

第 1 行

<template>
  <h1>{{ interval$ }}</h1>
</template>

在 HTML template 可直接使用在 subscriptions 定義的 Observable

Vue-rx 初體驗

  • 執行後會發現 interval$ 不斷地遞增
subscriptions: () => {
  const interval$ = interval(1000);

  return {
    interval$,
  };
},

RxJS 還會搭配許多 operator,不太可能只回傳 object,實務上我們常會寫成 function,最後再 return object。

Conclusion

  • 這就是最簡單的 Vue + Vue-rx,重點先將環境裝好,日後才能練習更進階的應用

Sample Code

完整的範例可以在我的 GitHub 上找到

Reference

Vue , vuejs/vue-rx

RxJS , ReactiveX/rxjs

egghead.io , Build Async Vue.js Apps with RxJS


以上所述就是小编给大家介绍的《Vue-rx 初體驗》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Mobilizing Web Sites

Mobilizing Web Sites

Layon, Kristofer / 2011-12 / 266.00元

Everyone has been talking about the mobile web in recent years, and more of us are browsing the web on smartphones and similar devices than ever before. But most of what we are viewing has not yet bee......一起来看看 《Mobilizing Web Sites》 这本书的介绍吧!

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具