组件 :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>

原文地址:http://www.cnblogs.com/zhulongxu/p/16796270.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性