最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

微信小程序代碼復(fù)用技巧總結(jié)大全

 更新時間:2026年03月23日 11:05:23   作者:yogalin1993  
在微信小程序中,你可以創(chuàng)建自定義組件,這些組件可以在不同的頁面和項目中重復(fù)使用,非常適合復(fù)用代碼,這篇文章主要介紹了微信小程序代碼復(fù)用技巧的相關(guān)資料,需要的朋友可以參考下

1.自定義組件復(fù)用

基本組件封裝

// components/common-button/common-button.js
Component({
  properties: {
    // 定義屬性
    type: {
      type: String,
      value: 'primary'  // primary/default/danger
    },
    text: String,
    disabled: Boolean
  },
  methods: {
    handleTap() {
      if (!this.data.disabled) {
        this.triggerEvent('tap')
      }
    }
  }
})
<!-- components/common-button/common-button.wxml -->
<button 
  class="common-btn {{type}} {{disabled ? 'disabled' : ''}}"
  bindtap="handleTap"
>
  {{text}}
</button>
/* components/common-button/common-button.wxss */
.common-btn {
  padding: 20rpx 40rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
}
.common-btn.primary {
  background: #07c160;
  color: #fff;
}
.common-btn.disabled {
  opacity: 0.5;
}

使用組件

// 頁面.json
{
  "usingComponents": {
    "common-button": "/components/common-button/common-button"
  }
}
<!-- 頁面.wxml -->
<common-button 
  text="提交" 
  type="primary" 
  bindtap="onSubmit"
/>

<common-button 
  text="取消" 
  type="default" 
  bindtap="onCancel"
/>

2.Behavior(行為)復(fù)用

創(chuàng)建公共Behavior

// behaviors/loading-behavior.js
module.exports = Behavior({
  data: {
    isLoading: false
  },
  methods: {
    // 顯示加載
    showLoading(text = '加載中...') {
      wx.showLoading({ title: text })
      this.setData({ isLoading: true })
    },
    
    // 隱藏加載
    hideLoading() {
      wx.hideLoading()
      this.setData({ isLoading: false })
    },
    
    // 帶加載狀態(tài)的請求
    async requestWithLoading(options) {
      this.showLoading()
      try {
        const res = await this.request(options)
        return res
      } finally {
        this.hideLoading()
      }
    }
  }
})

在多個組件中復(fù)用

// components/user-card/user-card.js
const loadingBehavior = require('../../behaviors/loading-behavior')

Component({
  behaviors: [loadingBehavior],
  methods: {
    async fetchUserInfo() {
      const data = await this.requestWithLoading({
        url: '/api/user/info'
      })
      this.setData({ userInfo: data })
    }
  }
})
// components/product-list/product-list.js
const loadingBehavior = require('../../behaviors/loading-behavior')

Component({
  behaviors: [loadingBehavior],
  methods: {
    async loadProducts() {
      const products = await this.requestWithLoading({
        url: '/api/products'
      })
      this.setData({ products })
    }
  }
})

3.Mixins模式實現(xiàn)

雖然小程序不直接支持Mixins,但可以通過Behavior模擬:

// behaviors/form-behavior.js
module.exports = Behavior({
  data: {
    formData: {},
    formErrors: {}
  },
  methods: {
    // 表單字段變化
    onFormChange(e) {
      const { field } = e.currentTarget.dataset
      const { value } = e.detail
      
      this.setData({
        [`formData.${field}`]: value,
        [`formErrors.${field}`]: ''
      })
    },
    
    // 表單驗證
    validateForm(rules) {
      const errors = {}
      let isValid = true
      
      Object.keys(rules).forEach(field => {
        const value = this.data.formData[field]
        const rule = rules[field]
        
        if (rule.required && !value) {
          errors[field] = rule.message || '該字段必填'
          isValid = false
        }
        // 更多驗證規(guī)則...
      })
      
      this.setData({ formErrors: errors })
      return isValid
    }
  }
})

4.高階組件模式

創(chuàng)建高階組件工廠

// utils/with-auth.js
function withAuth(Component) {
  return function(options) {
    const originalOnLoad = options.methods.onLoad || function() {}
    
    options.methods.onLoad = function(params) {
      // 檢查登錄狀態(tài)
      if (!this.checkAuth()) {
        wx.redirectTo({ url: '/pages/login/login' })
        return
      }
      
      originalOnLoad.call(this, params)
    }
    
    // 添加登錄檢查方法
    options.methods.checkAuth = function() {
      const token = wx.getStorageSync('token')
      return !!token
    }
    
    return Component(options)
  }
}

使用高階組件

// pages/user/user.js
import withAuth from '../../utils/with-auth'

const originalOptions = {
  data: { userInfo: {} },
  methods: {
    onLoad() {
      this.loadUserInfo()
    },
    loadUserInfo() {
      // 加載用戶信息
    }
  }
}

// 包裝原始配置
withAuth(Component)(originalOptions)

5.工具函數(shù)復(fù)用

按功能分類的工具函數(shù)

// utils/date-util.js
// 日期格式化
export function formatDate(date, format = 'YYYY-MM-DD') {
  if (!date) return ''
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  
  return format
    .replace('YYYY', year)
    .replace('MM', month)
    .replace('DD', day)
}

// 相對時間
export function relativeTime(date) {
  const now = new Date()
  const target = new Date(date)
  const diff = now - target
  
  const minutes = Math.floor(diff / 60000)
  if (minutes < 60) return `${minutes}分鐘前`
  
  const hours = Math.floor(minutes / 60)
  if (hours < 24) return `${hours}小時前`
  
  const days = Math.floor(hours / 24)
  if (days < 30) return `${days}天前`
  
  return formatDate(date)
}
// utils/request-util.js
// 統(tǒng)一的網(wǎng)絡(luò)請求
export function request(options) {
  const token = wx.getStorageSync('token')
  const header = {
    'Content-Type': 'application/json',
    ...options.header
  }
  
  if (token) {
    header['Authorization'] = `Bearer ${token}`
  }
  
  return new Promise((resolve, reject) => {
    wx.request({
      url: `https://api.example.com${options.url}`,
      method: options.method || 'GET',
      data: options.data,
      header,
      success: (result) => {
        if (result.statusCode === 200) {
          resolve(result.data)
        } else {
          reject(result.data)
        }
      },
      fail: reject
    })
  })
}

6.組合式復(fù)用

復(fù)雜組件的組合

// components/smart-form/smart-form.js
const formBehavior = require('../../behaviors/form-behavior')
const validationBehavior = require('../../behaviors/validation-behavior')

Component({
  behaviors: [formBehavior, validationBehavior],
  
  methods: {
    // 繼承自formBehavior的onFormChange
    // 繼承自validationBehavior的validateForm
    
    async onSubmit() {
      if (!this.validateForm(this.data.rules)) {
        return
      }
      
      // 提交表單
      const result = await this.submitData(this.data.formData)
      
      if (result.success) {
        this.triggerEvent('success', result.data)
      }
    }
  }
})

7.模板復(fù)用

WXML模板

<!-- templates/empty-state.wxml -->
<template name="emptyState">
  <view class="empty-container">
    <image src="{{icon}}" class="empty-icon" />
    <text class="empty-text">{{text}}</text>
    <button wx:if="{{showButton}}" bindtap="onButtonTap">
      {{buttonText}}
    </button>
  </view>
</template>

<template name="loading">
  <view class="loading-container">
    <image src="/images/loading.gif" class="loading-icon" />
    <text>{{text || '加載中...'}}</text>
  </view>
</template>

使用模板

<!-- 頁面.wxml -->
<import src="/templates/empty-state.wxml" />
<import src="/templates/loading.wxml" />

<view wx:if="{{isLoading}}">
  <template is="loading" data="{{text: '拼命加載中...'}}" />
</view>

<view wx:elif="{{isEmpty}}">
  <template 
    is="emptyState" 
    data="{{{
      icon: '/images/empty.png',
      text: '暫無數(shù)據(jù)',
      showButton: true,
      buttonText: '刷新試試'
    }}}" 
  />
</view>

8.樣式復(fù)用策略

創(chuàng)建樣式變量

/* styles/variables.wxss */
:root {
  --primary-color: #07c160;
  --danger-color: #fa5151;
  --text-color: #333;
  --border-color: #eee;
  --font-size-sm: 24rpx;
  --font-size-md: 28rpx;
  --font-size-lg: 32rpx;
  --border-radius: 8rpx;
}

復(fù)用樣式類

/* styles/common.wxss */
.flex-center {
  display: flex;
  align-items: center;
  justify-content: center;
}

.text-ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.hairline {
  position: relative;
}
.hairline::after {
  content: '';
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  border-bottom: 1rpx solid var(--border-color);
  transform: scaleY(0.5);
}

在頁面中引入

/* 頁面.wxss */
@import "/styles/variables.wxss";
@import "/styles/common.wxss";

.user-card {
  composes: flex-center;
  padding: 20rpx;
  border-radius: var(--border-radius);
  background: #fff;
}

9.數(shù)據(jù)狀態(tài)復(fù)用

創(chuàng)建全局狀態(tài)管理器

// store/user-store.js
class UserStore {
  constructor() {
    this._listeners = []
    this._userInfo = null
  }
  
  // 獲取用戶信息
  getUserInfo() {
    if (!this._userInfo) {
      this._userInfo = wx.getStorageSync('userInfo')
    }
    return this._userInfo
  }
  
  // 更新用戶信息
  setUserInfo(userInfo) {
    this._userInfo = userInfo
    wx.setStorageSync('userInfo', userInfo)
    this._notifyListeners()
  }
  
  // 訂閱變化
  subscribe(listener) {
    this._listeners.push(listener)
    return () => {
      const index = this._listeners.indexOf(listener)
      if (index > -1) this._listeners.splice(index, 1)
    }
  }
  
  _notifyListeners() {
    this._listeners.forEach(listener => listener(this._userInfo))
  }
}

// 導(dǎo)出單例
export default new UserStore()

在多個頁面中使用

// pages/profile/profile.js
import userStore from '../../store/user-store'

Page({
  onLoad() {
    // 獲取用戶信息
    this.setData({ 
      userInfo: userStore.getUserInfo() 
    })
    
    // 訂閱更新
    this.unsubscribe = userStore.subscribe((userInfo) => {
      this.setData({ userInfo })
    })
  },
  
  onUnload() {
    // 取消訂閱
    this.unsubscribe && this.unsubscribe()
  }
})

10.復(fù)用最佳實踐

1.按職責(zé)分層

utils/
  ├── date-util.js        # 日期處理
  ├── request-util.js     # 網(wǎng)絡(luò)請求
  ├── validate-util.js    # 驗證工具
  └── storage-util.js     # 存儲工具

behaviors/
  ├── form-behavior.js
  ├── loading-behavior.js
  └── auth-behavior.js

components/
  ├── common/            # 通用組件
  ├── business/          # 業(yè)務(wù)組件
  └── layout/            # 布局組件

mixins/                  # 混合功能
templates/               # 模板文件
styles/                  # 樣式文件

2.創(chuàng)建配置中心

// config/app-config.js
export default {
  // API配置
  api: {
    baseURL: 'https://api.example.com',
    timeout: 10000
  },
  
  // 頁面路徑
  pages: {
    login: '/pages/login/login',
    home: '/pages/home/home'
  },
  
  // 存儲鍵名
  storageKeys: {
    token: 'user_token',
    userInfo: 'user_info'
  }
}

3.文檔和示例

為每個復(fù)用組件創(chuàng)建示例頁面:

components/common-button/
  ├── common-button.js
  ├── common-button.wxml
  ├── common-button.wxss
  └── example/
      ├── example.js      # 使用示例
      └── example.wxml

復(fù)用帶來的好處

  1. 減少代碼量:避免重復(fù)編寫相同邏輯
  2. 便于維護:修改只需在一處進行
  3. 一致性:保證功能和行為統(tǒng)一
  4. 團隊協(xié)作:提供標(biāo)準(zhǔn)化的開發(fā)模式
  5. 包體積優(yōu)化:顯著減少重復(fù)代碼

通過合理的代碼復(fù)用,不僅能減小包體積,還能提升開發(fā)效率和代碼質(zhì)量。建議在項目初期就規(guī)劃好復(fù)用策略,建立代碼規(guī)范。

到此這篇關(guān)于微信小程序代碼復(fù)用技巧總結(jié)的文章就介紹到這了,更多相關(guān)微信小程序代碼復(fù)用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論

突泉县| 资阳市| 吴堡县| 涟源市| 泰来县| 通河县| 绍兴县| 百色市| 航空| 临江市| 阳新县| 遂宁市| 阿克苏市| 灌云县| 西乌珠穆沁旗| 榆中县| 车险| 宁强县| 勐海县| 玉溪市| 治县。| 隆安县| 漳平市| 黄浦区| 双流县| 通州区| 太和县| 嘉义市| 华宁县| 昔阳县| 青田县| 高雄市| 贺州市| 金塔县| 瑞安市| 北流市| 双鸭山市| 江北区| 锡林郭勒盟| 衡南县| 苍南县|