【微信小程序】项目开发-----百度翻译API接口开发微信翻译小程序

开发环境:

微信开发者工具 V1.02.1902010版本以上

开发语言:

JavaSript语言,HTML语言

API接口:

百度翻译开发平台开放接口

界面预览:

【微信小程序】项目开发-----百度翻译API接口开发微信翻译小程序_第1张图片

【微信小程序】项目开发-----百度翻译API接口开发微信翻译小程序_第2张图片

 

开发:

 

基础配置:

1.app.js

App({
  onLaunch: function () {
    // 展示本地存储能力
    this.globalData.curLang = wx.getStorageSync('curLang') || this.globalData.langList[0]
  },
  globalData: {
    curLang: {},
    langList: [
      {
        'chs': '英文',
        "lang": 'en',
        "index": 0
      },
      {
        'chs': '中文',
        'lang': 'zh',
        "index": 1
      },
      {
        'chs': '日语',
        'lang': 'jp',
        "index": 2
      },
      {
        'chs': '韩语',
        'lang': 'kor',
        "index": 3
      },
      {
        'chs': '法语',
        'lang': 'fra',
        "index": 4
      },
      {
        'chs': '德语',
        'lang': 'de',
        "index": 5
      },
      {
        'chs': '俄语',
        'lang': 'ru',
        "index": 6
      },
      {
        'chs': '泰语',
        'lang': 'th',
        "index": 7
      },
      {
        'chs': '西班牙语',
        'lang': 'spa',
        "index": 8
      },
      {
        'chs': '阿拉伯语',
        'lang': 'ara',
        "index": 9
      },
      {
        'chs': '意大利语',
        'lang': 'it',
        "index": 10
      },
      {
        'chs': '葡萄牙语',
        'lang': 'pt',
        "index": 11
      }
    ]
  }
})

2.app.json

{
  "pages": [
    "pages/index/index",
    "pages/change/change",
    "pages/history/history"
  ],
  "window": {
    "backgroundTextStyle": "light",
    "navigationBarBackgroundColor": "#000080",
    "navigationBarTitleText": "Hi 翻译",
    "navigationBarTextStyle": "white",
    "backgroundColor": "#4b3c96"
  },
  "tabBar": {   
    "borderStyle": "white",
    "position": "bottom",
    "color": "#bfbfbf",
    "selectedColor": "#1c1b21",
    "list": [
      {
        "pagePath": "pages/index/index",
        "text": "文本翻译",
        "iconPath": "imgs/icon-1.png",
        "selectedIconPath": "imgs/sel-icon-1.png"
      },
      {
        "pagePath": "pages/history/history",
        "text": "历史记录",
        "iconPath": "imgs/icon-2.png",
        "selectedIconPath": "imgs/sel-icon-2.png"
      }
    ]
  }
}

3.app.wxss

@import "./assets/iconfont/iconfont.wxss";

.container {
  padding: 0;
  background-color:#f7f8f9;
  height: 100vh;
  display: flex;
  flex-direction:column;
  box-sizing: border-box;
  font-size: 30rpx;
  color: #333;
} 

.copyright {
  align-self: center;
  flex: 1;
  display: flex;
  align-items: flex-end;
  padding-bottom: 20rpx;
  font-size: 28rpx;
  color:#999;
}

.view-hover {
  background-color: #f3f3f3!important;
}

3.project.conflg.json

{
	"description": "项目配置文件。",
	"packOptions": {
		"ignore": []
	},
	"setting": {
		"urlCheck": true,
		"es6": true,
		"postcss": true,
		"minified": true,
		"newFeature": true
	},
	"compileType": "miniprogram",
	"libVersion": "2.0.4",
	"appid": "wxcee51eaafd89eb23",
	"projectname": "weixin-test",
	"isGameTourist": false,
	"condition": {
		"search": {
			"current": -1,
			"list": []
		},
		"conversation": {
			"current": -1,
			"list": []
		},
		"game": {
			"currentL": -1,
			"list": []
		},
		"miniprogram": {
			"current": -1,
			"list": []
		}
	}
}

utils配置:

1.api.js

import md5 from './md5.min.js'

const appid = '20190528000302826'
const key = 'e2A2h832pG1PRubLj22_'
//如果你不传递第二个参数那么这个参数默认就是 { from: 'auto', to: 'auto'},
//如果你第二个参数里没有传from那么默认就是from的值为'auto',如果没传to默认to的值也为'auto',
//如果传了from或者to就是你传递的值,其实就是{from: 形参, to: 形参}
function translate(q, { from = 'auto', to = 'auto' } = { from: 'auto', to: 'auto' }) {
  return new Promise((resolve, reject) => {
    let salt = Date.now()
    let sign = md5(`${appid}${q}${salt}${key}`)
    wx.request({
      url: 'https://fanyi-api.baidu.com/api/trans/vip/translate',
      data: {
        q,
        from,
        to,
        appid,
        salt,
        sign
      },
      success(res) {
        if (res.data && res.data.trans_result) {
          // console.log(res,'1')
          // console.log(res.data,'2')
          // console.log(res.data.trans_result,'3')
          resolve(res.data)
        } else {
          reject({ status: 'error', msg: '翻译失败' })
          wx.showToast({
            title: '翻译失败',
            icon: 'none',
            duration: 3000
          })
        }
      },
      fail() {
        reject({ status: 'error', msg: '翻译失败' })
        wx.showToast({
          title: '网络异常',
          icon: 'none',
          duration: 3000
        })
      }
    })
  })
}
module.exports.translate = translate

2.util.js

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

module.exports = {
  formatTime: formatTime
}

index配置:

1.index.js

//index.js
//获取应用实例
import { translate } from '../../utils/api.js'
const app = getApp()

Page({
  data: {
    query: '',   //输入文字
    hideClearIcon: true,   //close icon显现状态
    result: [],   //译文结果
    curLang: {}   //当前语言
  },
  onLoad: function (options) {  //翻译历史页通过 reLaunch 跳转,重新加载
    console.log('onload..')
    console.log(options)
    if (options.query) {
      this.setData({ query: options.query })
      this.setData({ 'hideClearIcon': false })   //让icon-close显现
    }
  }, 
  onShow: function () {
    if (this.data.curLang.lang !== app.globalData.curLang.lang) {
      this.setData({ curLang: app.globalData.curLang })
      this.onConfirm()
    }

  },
  onInput: function (e) {
    //传递用户输入的数据、close的展示跟隐藏
    this.setData({ 'query': e.detail.value })
    if (this.data.query.length > 0) {   //输入时字体图标出现
      this.setData({ 'hideClearIcon': false })
    } else {
      this.setData({ 'hideClearIcon': true })
    }

    console.log('focus')
  },
  onTapClose: function () {
    //用户点击close的事件
    this.setData({ query: '', hideClearIcon: true })
    //如果不需要保留译文结果,也可以删除
    this.setData({ result: '' }) 
    console.log('clearAll')
  },
  onConfirm: function () {
    //翻译
    if (!this.data.query) return  //空文本的时候不进行翻译
    translate(this.data.query, { from: 'auto', to: this.data.curLang.lang }).then(res => {
      //调用 api.js 里面的 Promise
      this.setData({ 'result': res.trans_result })

      let history = wx.getStorageSync('history') || []
      history.unshift({ query: this.data.query, result: res.trans_result[0].dst })
      history.length = history.length > 10 ? 10 : history.length
      wx.setStorageSync('history', history)
    })
  }
})

2.index.wxml

 

  
     
    
      
        翻译成{{curLang.chs}}
        
       
    

  
  
    
    
      
    
    
      译文
      
        {{item.dst}}
      
    
  

3.index.wxss


.change {
  color: #8995a1;
  font-size: 24 rpx;
  padding: 20rpx 40rpx;
  display: flex;
  align-items: center;
}
.change .icon-right {
  color: #888;
}
.change .icon-down {
  color: #8995a1;
  font-size: 20rpx;
}

.input-area {
  position: relative;
}
.textarea-wrap {
  background: #fff;
  border-bottom: 5px solid #F5F5F5;
}
.input-area textarea {
  background-color: #fff;
  padding: 30rpx 0 30rpx 30rpx;
  width: calc(100% - 48rpx);
  margin: 0;
  box-sizing: border-box;
}
.input-area .icon-close {
  position: absolute;
  right: 12rpx;
  top: 20rpx;
  z-index: 100;
  font-size: 40rpx;
  color: #888;
}

.input-area .text-area {
  min-height: 80rpx;
  padding: 30rpx;
  background-color: #fff;
}

.input-area .text-title {
  font-size: 28rpx;
  color: #8995a1;
}

.input-area .text-result {
  padding: 20rpx 0;
}

翻译主页:

1.change.js

const util = require('../../utils/util.js')
const app = getApp()
Page({
  data: {
    curLang: {},
    langList: app.globalData.langList  //存储当前语言
  },
  onShow: function () {
    this.setData({ curLang: app.globalData.curLang })
  },
  onTapItem: function (e) {
    let langObj = e.currentTarget.dataset
    wx.setStorageSync('language', langObj)
    this.setData({ 'curLang': langObj })
    app.globalData.curLang = langObj
    wx.switchTab({ url: '/pages/index/index' })  //跳转页面
  }
})

2.change.wxml


  翻译成
  
    
      {{language.chs}} 
      
    
  

3.change.wxss

/* * change.wxss * */

.container {
  background: #f8f8f8;
}
.lang-list {
  display: flex;
  flex-direction: column;
}
.title {
  background: #fff;
  border-bottom: 1px solid #F5F5F5;
  padding: 20rpx 40rpx;
  color: #aaa;
  font-size: 28rpx;
}


.item {
  padding-left: 40rpx;
  background-color: #fff;
}
.item-inner {
  display: flex;
  align-items: center;
  border-top: 1px solid #ececec;
  padding:  20rpx 40rpx 20rpx 0;
  
}

.item .txt {
  flex: 1;
}
.item .iconfont {
  margin-left: auto;
  color: #aaa;
}

.item:nth-child(2) .item-inner {
  border-top: none;
}

历史查看主页:

1.history.js

const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    history: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  onShow: function () {
    this.setData({ history: wx.getStorageSync('history') })
  },

  onTapItem: function (e) {
    wx.reLaunch({
      url: `/pages/index/index?query=${e.currentTarget.dataset.query}`
    })
  },

  onClearHistory: function(){
    this.setData({history: []})  //将显示变为空
    wx.clearStorage('history')   //并清除Storage历史记录
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})

2.history.wxml



  
    
      文本:
      清除历史
    
    
      {{item.query}}
      {{item.result}}
    
  

3.history.wxss

.history-list {
  display: flex;
  flex-direction: column;
  padding: 40rpx;
}
.header {
  display: flex;
}
.title {
  flex:1;
  font-size: 26rpx;
  color: #8995a1;
}
.icon-close {
  margin-left: auto;
  color: #aaa;
  font-size: 26rpx;
}
.item {
  margin-top: 40rpx;
}

.item .query {
  color: #8995a1;
}

.item .result {
  margin-top: 16rpx;
}

图片配置:

【微信小程序】项目开发-----百度翻译API接口开发微信翻译小程序_第3张图片

开发界面:

【微信小程序】项目开发-----百度翻译API接口开发微信翻译小程序_第4张图片

【微信小程序】项目开发-----百度翻译API接口开发微信翻译小程序_第5张图片

Api构建:

【微信小程序】项目开发-----百度翻译API接口开发微信翻译小程序_第6张图片

【微信小程序】项目开发-----百度翻译API接口开发微信翻译小程序_第7张图片

 

 

源码下载:

https://download.csdn.net/download/jockliu/11255020

 

你可能感兴趣的:(项目开发)