uniapp公告

冷空气的清晰發表於2024-08-26
<template>
  <view class="page">
    <!-- 公告欄 -->
    <scroll-view
      scroll-y="true"  <!-- 啟用垂直滾動 -->
      class="notice-container"  <!-- 應用定義的樣式類 -->
      :scroll-into-view="currentView"  <!-- 根據當前檢視ID進行滾動 -->
      :scroll-with-animation="true"  <!-- 滾動時啟用動畫效果 -->
    >
      <!-- 使用 v-for 迴圈生成公告項 -->
      <view v-for="(item, index) in notices" 
            :key="index"  <!-- 設定唯一鍵值,最佳化渲染 -->
            :id="'notice-' + index"  <!-- 設定每個公告項的唯一ID,供滾動定位使用 -->
            class="notice-item"> <!-- 應用定義的公告項樣式類 -->
        {{ item }}  <!-- 顯示公告內容 -->
      </view>
    </scroll-view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      // 公告列表,包含多個公告內容
      notices: [
        '公告1:這裡是第一條公告資訊',
        '公告2:這裡是第二條公告資訊',
        '公告3:這裡是第三條公告資訊',
      ],
      // 當前顯示的公告索引
      currentIndex: 0,
    };
  },
  computed: {
    // 計算當前需要滾動到的檢視ID
    currentView() {
      return 'notice-' + this.currentIndex;
    },
  },
  mounted() {
    // 元件掛載後啟動自動滾動
    this.startScroll();
  },
  methods: {
    // 啟動滾動,使用定時器每隔3秒更新一次currentIndex
    startScroll() {
      setInterval(() => {
        // 每次呼叫將當前索引增加1,當索引超過公告數量時重置為0
        this.currentIndex = (this.currentIndex + 1) % this.notices.length;
      }, 3000); // 每3秒滾動一次
    },
  },
};
</script>

<style>
.notice-container {
  height: 50rpx; /* 設定滾動區域的高度 */
  overflow: hidden; /* 隱藏超出區域的內容 */
}

.notice-item {
  height: 50rpx; /* 每個公告項的高度,確保內容適應容器 */
  line-height: 50rpx; /* 設定行高,使文字在垂直方向居中 */
  text-align: center; /* 文字水平居中 */
  font-size: 16px; /* 設定字型大小 */
  color: #333; /* 設定文字顏色 */
}
</style>

相關文章