收藏,取消收藏文章组件
组件 :collectArticle
<template> <div class="collect-container"> <van-loading v-if="isLoading" type="spinner" color="#1989fa"></van-loading> <van-icon v-else :color="value ? '#ff0000' : '#777'" :name="value ? 'star' : 'star-o'" @click="clickHandler" /> </div> </template> <script> import { delCollectArticleApi, addCollectArticleApi } from "@/api/Article"; export default { name: "collectArticle", data() { return { isLoading: false, }; }, props: { // 是否收藏 value: { type: Boolean, required: true, }, // 文章的 id articleId: { type: [String, Number], required: true, }, }, methods: { async clickHandler() { // 判断是否登录了,未登录不允许点击 if (!this.$store.state.user) return this.$toast.fail("登录后才可以操作"); // 节流阀 => 开始转圈圈 this.isLoading = true; try { if (this.value) { // 去过已经收藏就取消 await delCollectArticleApi(this.articleId); } else { // 如果未收藏就收藏 await addCollectArticleApi({ target: this.articleId, }); } // 更新视图(按钮的状态) // this.value = !this.value; // vue 是单向数据流传递 this.$emit("input", !this.value); } catch (error) { console.log({ error }); this.$toast.fail("操作失败"); } this.isLoading = false; }, }, }; </script> <style> </style>
父组件传值 :
<!-- 收藏文章组件 --> <collectArticle :article-id="articleInfo.art_id" :value="articleInfo.is_collected" @input="articleInfo.is_collected = $event" ></collectArticle>
写成语法糖 v-model
<collectArticle :article-id="articleInfo.art_id" v-model="articleInfo.is_collected" ></collectArticle>