iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 23
0
Modern Web

Vue菜鳥的自我學習days系列 第 23

23.Rxjs 處理非同步2

再來修改 ProductList.vue 與 ProductInfo.vue,由於 product-service 回傳的內容已經更改為 Observable 物件,因應變動 created 的資料處理邏輯
在 created 訂閱 productService.get() 回傳的 observable 物件,並處理 next() 觸發事件

this.$subscribeTo(productService.get(), (res) => {
this.products = res.response;
});

當使用 VueRx 的 $subscribeTo 時,component 在銷毀時會幫我們處理 Observable 的 unsubscribe,因此不需
要另外在 destroy 時 unsubcribe
完整程式碼

<script>
import productService from '@/services/product-service';
export default {
name: 'ProductList',
data() {
return {
products: [],
};
},
created() {
this.$subscribeTo(productService.get(), (res) => {
this.products = res.response;
});
},
methods: {
onProductClick(product) {
this.$router.push({ name: 'productInfo', params: { id: product.id } });
},
},
};
</script>

ProductInfo.vue

<script>
import productService from '@/services/product-service';
export default {
name: 'ProductInfo',
data() {
return {
product: {},
quantity: 0,
};
},
created() {
this.$subscribeTo(productService.get(this.$route.params.id), (res) => {
this.product = res.response;
});
},
computed: {
amount() {
return this.product.price * this.quantity;
},
},
methods: {
onBackClick() {
this.$router.back();
},
},
};
</script>

上一篇
22. Rxjs 處理非同步
下一篇
24.Rxjs 處理非同步3
系列文
Vue菜鳥的自我學習days39
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言