uniapp 组件中可以用onshow吗?-icode9专业技术文章分享

2024/12/18 6:03:12

本文主要是介绍uniapp 组件中可以用onshow吗?-icode9专业技术文章分享,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

在 UniApp 中,组件本身并没有 onShow 生命周期钩子,但你可以通过页面的 onShow 钩子来间接实现类似的功能。如果你希望在组件中执行某些操作,可以在父页面的 onShow 钩子中调用组件的方法或更新组件的状态。

两种实现方式

1. 在父页面的 onShow 钩子中调用组件的方法

假设你有一个父页面 Index.vue 和一个子组件 NotificationComponent.vue,你可以在父页面的 onShow 钩子中调用子组件的方法。

父页面 Index.vue
<template>
  <view>
    <NotificationComponent ref="notificationComponent" />
  </view>
</template>

<script>
import NotificationComponent from '@/components/NotificationComponent.vue';

export default {
  components: {
    NotificationComponent
  },
  onShow() {
    this.$refs.notificationComponent.handleOnShow();
  }
}
</script>

Vue
子组件 NotificationComponent.vue
<template>
  <view>
    <!-- 消息通知 -->
    <u-popup :show="notice_status" :round="120" @close="notice_status=false" mode="top" bgColor="transparent" :overlay="false">
      <view class="notice_bg">
        <view class="notice_title flex-between">
          <view class="flex-align-center">
            <image class="notice_notice" src="@/static/images/common/notice.png" />
            {{notice_info.title}}
          </view>
          <view>
            {{notice_info.time}}
          </view>
        </view>
        <view class="notice_tips">
          {{notice_info.content}}
        </view>
      </view>
    </u-popup>
    
    <!-- 考试通知 -->
    <u-popup :show="test_status" :round="120" @close="test_status=false" mode="center" bgColor="transparent">
      <view class="test_bg">
        <view class="test_title">测试任务提醒</view>
        <view class="test_tip">老师给你发送了测试试卷,快来测试一下吧!</view>
        <view class="test_paper">试卷:<text style="font-weight: bold;">{{info.name}}</text></view>
        <view class="test_content">
          <view>题目数量:<text style="color: #43adef;">{{info.num}}题</text></view>
          <view>发送时间:<text style="color: #43adef;">{{info.time}}</text></view>
        </view>
        <view class="test_button" @click="startTest">进入测试</view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import {
  getPaperStatusApi
} from '@/api/questionBank/index.js';
import {
  getWordPaperStatusApi
} from '@/api/wordPaper/index.js';
import {
  mapGetters
} from 'vuex';

export default {
  data() {
    return {
      notice_status: false,
      notice_info: { //通知数据
        title: '',
        time: '',
        content: '',
        type: ''
      },
      test_status: false,
      info: {
        name: '', //试卷名称
        num: 0, //小题数量
        time: '', //发卷时间
        type: 3, //3:习题试卷,6:词汇试卷
        paper_id: '', //习题试卷的试卷id
        paper_exam_id: '', //考试记录的id
        paper_exam_record_id: '',
        word_paper_id: '',
      }
    }
  },
  computed: {
    ...mapGetters([
      'notice_types'
    ])
  },
  methods: {
    getNotice() {
      const now = new Date();
      const hours = now.getHours().toString().padStart(2, '0'); // 获取小时并确保是两位数
      const minutes = now.getMinutes().toString().padStart(2, '0'); // 获取分钟并确保是两位数
      this.notice_info.time = `${hours}:${minutes}`;

      const pages = getCurrentPages();
      const currentPage = pages[pages.length - 1];
      const currentPageRoute = currentPage.route; // 获取当前页面路由

      if (this.notice_types.includes('1')) {
        this.handleNotice('1', '同步课程通知', '老师为你更新了同步课程');
      } else if (this.notice_types.includes('2')) {
        this.handleNotice('2', '任务课程通知', '老师为你更新了任务课程', 'pages/index/index');
      } else if (this.notice_types.includes('5')) {
        this.handleNotice('5', '智能复习通知', '老师为你更新了智能复习规则', 'pages/review/review');
      } else if (this.notice_types.includes('3')) { //习题试卷
        this.getPaper();
      } else if (this.notice_types.includes('6')) { //词汇试卷
        this.getWordPaper();
      }
    },

    handleNotice(type, title, content, redirectPage = null) {
      this.notice_info.title = title;
      this.notice_info.content = content;
      this.notice_info.type = type;
      this.notice_status = true;

      var notice_types = this.notice_types.filter(item => item !== type);
      this.$store.commit('notice/set_notice_types', notice_types);

      var that = this;
      if (redirectPage && currentPageRoute === redirectPage) {
        setTimeout(function() {
          that.notice_status = false;
        }, 3000);
      } else if (redirectPage) {
        setTimeout(function() {
          uni.redirectTo({
            url: '/' + redirectPage
          });
        }, 2000);
      } else {
        setTimeout(function() {
          that.notice_status = false;
        }, 3000);
      }
    },

    async getPaper() {
      const { data: res } = await getPaperStatusApi();
      if (res.data) {
        this.test_status = true;
        this.info.name = res.data.paper.name;
        this.info.num = res.data.paper.question_item_num;
        this.info.time = res.data.exam_time;
        this.info.paper_id = res.data.paper_id;
        this.info.paper_exam_id = res.data.paper_exam_id;
        this.info.paper_exam_record_id = res.data.paper_exam_record_id;
        this.info.type = '3';
        console.log(this.info);
      }
    },

    async getWordPaper() {
      const { data: res } = await getWordPaperStatusApi();
      if (res.data) {
        this.test_status = true;
        this.info.name = res.data.name;
        this.info.num = res.data.num;
        this.info.time = res.data.exam_time;
        this.info.word_paper_id = res.data.word_paper_id;
        this.info.type = '6';
      }
    },

    startTest() {
      var notice_types = this.notice_types.filter(item => item !== this.info.type);
      this.$store.commit('notice/set_notice_types', notice_types);

      if (this.info.type == '3') { //习题试卷
        this.test_status = false;
        uni.navigateTo({
          url: '/pages/questionBank/components/startTest/startTest?id=' + this.info.paper_id +
            '&paper_exam_id=' +
            this.info.paper_exam_id + '&paper_exam_record_id=' + this.info.paper_exam_record_id
        });
      }
    },

    handleOnShow() {
      this.getNotice();
    }
  }
}
</script>

Vue

2. 使用 watch 监听路由变化

你也可以在组件中使用 watch 监听路由变化,从而在页面显示时执行某些操作。

子组件 NotificationComponent.vue
<template>
  <view>
    <!-- 消息通知 -->
    <u-popup :show="notice_status" :round="120" @close="notice_status=false" mode="top" bgColor="transparent" :overlay="false">
      <view class="notice_bg">
        <view class="notice_title flex-between">
          <view class="flex-align-center">
            <image class="notice_notice" src="@/static/images/common/notice.png" />
            {{notice_info.title}}
          </view>
          <view>
            {{notice_info.time}}
          </view>
        </view>
        <view class="notice_tips">
          {{notice_info.content}}
        </view>
      </view>
    </u-popup>
    
    <!-- 考试通知 -->
    <u-popup :show="test_status" :round="120" @close="test_status=false" mode="center" bgColor="transparent">
      <view class="test_bg">
        <view class="test_title">测试任务提醒</view>
        <view class="test_tip">老师给你发送了测试试卷,快来测试一下吧!</view>
        <view class="test_paper">试卷:<text style="font-weight: bold;">{{info.name}}</text></view>
        <view class="test_content">
          <view>题目数量:<text style="color: #43adef;">{{info.num}}题</text></view>
          <view>发送时间:<text style="color: #43adef;">{{info.time}}</text></view>
        </view>
        <view class="test_button" @click="startTest">进入测试</view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import {
  getPaperStatusApi
} from '@/api/questionBank/index.js';
import {
  getWordPaperStatusApi
} from '@/api/wordPaper/index.js';
import {
  mapGetters
} from 'vuex';

export default {
  data() {
    return {
      notice_status: false,
      notice_info: { //通知数据
        title: '',
        time: '',
        content: '',
        type: ''
      },
      test_status: false,
      info: {
        name: '', //试卷名称
        num: 0, //小题数量
        time: '', //发卷时间
        type: 3, //3:习题试卷,6:词汇试卷
        paper_id: '', //习题试卷的试卷id
        paper_exam_id: '', //考试记录的id
        paper_exam_record_id: '',
        word_paper_id: '',
      }
    }
  },
  computed: {
    ...mapGetters([
      'notice_types'
    ])
  },
  watch: {
    '$route': {
      handler() {
        this.getNotice();
      },
      immediate: true // 立即执行一次
    }
  },
  methods: {
    getNotice() {
      const now = new Date();
      const hours = now.getHours().toString().padStart(2, '0'); // 获取小时并确保是两位数
      const minutes = now.getMinutes().toString().padStart(2, '0'); // 获取分钟并确保是两位数
      this.notice_info.time = `${hours}:${minutes}`;

      const pages = getCurrentPages();
      const currentPage = pages[pages.length - 1];
      const currentPageRoute = currentPage.route; // 获取当前页面路由

      if (this.notice_types.includes('1')) {
        this.handleNotice('1', '同步课程通知', '老师为你更新了同步课程');
      } else if (this.notice_types.includes('2')) {
        this.handleNotice('2', '任务课程通知', '老师为你更新了任务课程', 'pages/index/index');
      } else if (this.notice_types.includes('5')) {
        this.handleNotice('5', '智能复习通知', '老师为你更新了智能复习规则', 'pages/review/review');
      } else if (this.notice_types.includes('3')) { //习题试卷
        this.getPaper();
      } else if (this.notice_types.includes('6')) { //词汇试卷
        this.getWordPaper();
      }
    },

    handleNotice(type, title, content, redirectPage = null) {
      this.notice_info.title = title;
      this.notice_info.content = content;
      this.notice_info.type = type;
      this.notice_status = true;

      var notice_types = this.notice_types.filter(item => item !== type);
      this.$store.commit('notice/set_notice_types', notice_types);

      var that = this;
      if (redirectPage && currentPageRoute === redirectPage) {
        setTimeout(function() {
          that.notice_status = false;
        }, 3000);
      } else if (redirectPage) {
        setTimeout(function() {
          uni.redirectTo({
            url: '/' + redirectPage
          });
        }, 2000);
      } else {
        setTimeout(function() {
          that.notice_status = false;
        }, 3000);
      }
    },

    async getPaper() {
      const { data: res } = await getPaperStatusApi();
      if (res.data) {
        this.test_status = true;
        this.info.name = res.data.paper.name;
        this.info.num = res.data.paper.question_item_num;
        this.info.time = res.data.exam_time;
        this.info.paper_id = res.data.paper_id;
        this.info.paper_exam_id = res.data.paper_exam_id;
        this.info.paper_exam_record_id = res.data.paper_exam_record_id;
        this.info.type = '3';
        console.log(this.info);
      }
    },

    async getWordPaper() {
      const { data: res } = await getWordPaperStatusApi();
      if (res.data) {
        this.test_status = true;
        this.info.name = res.data.name;
        this.info.num = res.data.num;
        this.info.time = res.data.exam_time;
        this.info.word_paper_id = res.data.word_paper_id;
        this.info.type = '6';
      }
    },

    startTest() {
      var notice_types = this.notice_types.filter(item => item !== this.info.type);
      this.$store.commit('notice/set_notice_types', notice_types);

      if (this.info.type == '3') { //习题试卷
        this.test_status = false;
        uni.navigateTo({
          url: '/pages/questionBank/components/startTest/startTest?id=' + this.info.paper_id +
            '&paper_exam_id=' +
            this.info.paper_exam_id + '&paper_exam_record_id=' + this.info.paper_exam_record_id
        });
      }
    }
  }
}
</script>

Vue

标签: 来源:

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。



这篇关于uniapp 组件中可以用onshow吗?-icode9专业技术文章分享的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程