微信小程序--中英文切換(2)


需求:第一次打開時的小程序的語言為本機的系統語言,在小程序中進行語言設置后再次打開其語言保持設置不變。

流程圖

 

1.獲取本機系統設置

wx.getSystemInfoSync()

獲取系統異步接口:

try{
    wx.getSystemInfo({
      success: function(res) {
        console.log(res.model)
        console.log(res.pixelRatio)
        console.log(res.windowWidth)
        console.log(res.windowHeight)
        console.log(res.language)
        console.log(res.version)
        console.log(res.platform)
 
    } })
}

獲取系統同步接口:

try {
  var res = wx.getSystemInfoSync()
  console.log(res.model)
  console.log(res.pixelRatio)
  console.log(res.windowWidth)
  console.log(res.windowHeight)
  console.log(res.language)
  console.log(res.version)
  console.log(res.platform)
} catch (e) {
  // Do something when catch error
}

在本文中只需獲取language信息即可。console.log(key),用於在運行后console中查看key的內容信息。

2.獲取緩存信息

wx.getStorageSync()

從本地緩存中同步獲取key對應的內容:

try {
  var value = wx.getStorageSync('key')
  if (value) {
      // Do something with return value
  }
} catch (e) {
  // Do something when catch error
}

key是我們所需的緩存內容的名字。

從本地緩存中異步獲取key對應的內容:

wx.getStorageInfo({
  success: function(res) {
    console.log(res.keys)
    console.log(res.currentSize)
    console.log(res.limitSize)
  }
})

因為語言設置為全局設置,所以設置放在app.js中,在頁面的js中調用app.js。

//third.js
var
app = getApp();

源代碼

//app.js
App({

  onLaunch: function (options) {
    //讀取系統緩存
    var value = wx.getStorageSync('language')

    //系統緩存不存在
    if (value == "") {
               var res = wx.getSystemInfoSync()  //讀取手機信息
      this.language = res.language     // 這個地方用this          }else if(value == "zh_CN"){
      console.log("系統緩存為'zh_CN'")  //系統緩存為"zh_CN"
          this.language = "zh_CN"
    }else{
           this.language = "zh_EN" //系統緩存為"zh_EN"
    }
  },
  language:""//全局變量
}

其他的語言設置部分同上節。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM