【微信小程序】项目开发-----百度翻译API接口开发微信翻译小程序
开发环境:
微信开发者工具 V1.02.1902010版本以上
开发语言:
JavaSript语言,HTML语言
API接口:
百度翻译开发平台开放接口
界面预览:
开发:
基础配置:
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() + 1const 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 里面的 Promisethis.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.lengthwx.setStorageSync('history', history)})}
})
2.index.wxml
<!--index.wxml-->
<view class="container"><view class="change"><!-- navigator导航 --><navigator url="/pages/change/change" hover-class="navigator-hover"><block><text>翻译成{{curLang.chs}}</text><text class="iconfont icon-down"></text></block> </navigator></view><view class="input-area"><text class="iconfont icon-close" hidden="{{hideClearIcon}}" bindtap='onTapClose'></text><view class="textarea-wrap"><textarea placeholder='查单词或翻译句子' placeholder-style='color: #8995a1' bindinput='onInput' bindconfirm='onConfirm' bindblur='onConfirm' value="{{query}}"></textarea></view><view class="text-area"><view class="text-title">译文</view><view class="text-result" wx:for="{{result}}" wx:key="index"><text selectable="true">{{item.dst}}</text></view></view></view>
</view>
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.datasetwx.setStorageSync('language', langObj)this.setData({ 'curLang': langObj })app.globalData.curLang = langObjwx.switchTab({ url: '/pages/index/index' }) //跳转页面}
})
2.change.wxml
<view class="container lang-list"><view class="title">翻译成</view><view class="item" data-chs="{{language.chs}}" data-lang="{{language.lang}}" data-index="{{index}}" wx:for="{{langList}}" wx:key="index" wx:for-item="language" bindtap='onTapItem' hover-class="view-hover"><view class="item-inner"><text class="txt">{{language.chs}}</text> <text class="iconfont icon-duihao" wx:if="{{index===curLang.index}}"></text></view></view>
</view>
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
<scroll-view scroll-y class="container"><view class="history-list"><view class="header"><text class="title">文本:</text><text bindtap='onClearHistory' class="iconfont icon-close">清除历史</text></view><view class="item" wx:for="{{history}}" wx:key="index" bindtap='onTapItem' data-query="{{item.query}}" data-langId="{{item.langIndex}}"><view class="query">{{item.query}}</view><view class="result">{{item.result}}</view></view></view>
</scroll-view>
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构建:
源码下载:
https://download.csdn.net/download/jockliu/11255020
【微信小程序】项目开发-----百度翻译API接口开发微信翻译小程序相关推荐
- 微信小程序城市定位(百度地图API)
概述 微信小程序提供一些API(地址)用于获取当前用户的地理位置等信息,但无论是wx.getLocation,还是wx.chooseLocation均没有单独的字段表示国家与城市信息,仅有经纬度信息. ...
- api 定位 微信小程序 精度_微信小程序城市定位(百度地图API)
概述 微信小程序提供一些API(地址)用于获取当前用户的地理位置等信息,但无论是wx.getLocation,还是wx.chooseLocation均没有单独的字段表示国家与城市信息,仅有经纬度信息. ...
- 视频教程-微信小程序项目实战:高仿iOS计算器-微信开发
微信小程序项目实战:高仿iOS计算器 东北大学计算机专业硕士研究生,欧瑞科技创始人&CEO,曾任国内著名软件公司项目经理,畅销书作者,企业IT内训讲师,CSDN学院专家讲师,制作视频课程超过1 ...
- 12月15-16日:跟着猫叔写代码学习api接口开发小程序
猫叔博客地址:fast-小程序:todolist项目文档汇总 - 猫叔饭-写代码的猫叔个人博客 视频地址:todolist实战课程-fastadmin结合微信小程序开发实例 api接口开发和对接_哔哩 ...
- IOS开发百度地图API入门到精通-用点生成路线,导航,气泡响应
(转)IOS开发百度地图API入门到精通-用点生成路线,导航,气泡响应 IOS百度地图API开发自定义气泡,点击气泡自动生成路线,以及拖拽 IOS百度地图开发POISearch搜索附近停车场,附近加油 ...
- IOS开发百度地图API
IOS百度地图API开发自定义气泡,点击气泡自动生成路线,以及拖拽 IOS百度地图开发POISearch搜索附近停车场,附近加油站 IOS百度地图视角跳到用户当前位置 IOS百度地图开发实时路况 IO ...
- IOS开发百度地图API-用点生成路线,导航,气泡响应
原地址:http://blog.sina.com.cn/s/blog_68661bd80101k4rx.html IOS百度地图API开发自定义气泡,点击气泡自动生成路线,以及拖拽 IOS百度地图开发 ...
- 转:IOS开发百度地图API-用点生成路线,导航,气泡响应
IOS百度地图API开发自定义气泡,点击气泡自动生成路线,以及拖拽 IOS百度地图开发POISearch搜索附近停车场,附近加油站 IOS百度地图视角跳到用户当前位置 IOS百度地图开发实时路况 IO ...
- python百度翻译api申请网页版_python3调用百度翻译api接口实现全过程
现在很都平台的翻译api接口都开始收费了,比如谷歌.微软.yandex等等,注册非常麻烦,而且要钱,目前就百度还剩下一个最基础的翻译api不需要钱,今天我要和大家分享的是怎样使用python3调用百度 ...
- 微信API接口、微信二次开发API调用
微信API接口.微信二次开发API调用 微信协议接口调用-加微信好友及通过好友请求 加微信好友 /** * 微信自动添加好友 * @author wechatno:tangjin ...
最新文章
- 旷视提Circle Loss,统一优化视角,革新深度特征学习范式 | CVPR 2020
- CVPR 2021 | MI-AOD: 少量样本实现高检测性能
- Jquery源码解析-设计理念
- 饿了么研发总监马尧:外卖推荐算法中有哪些机制与手段?
- Java服务GC参数调优案例
- Python入门学习笔记(5)
- Spring 源码解析 -- SpringWeb过滤器Filter解析
- 给前端开发人员上几道菜~
- Python 获取父级文件夹的名字
- [转]百度地图的一些应用方法
- 杭电 hdu 2002
- bigemap功能介绍
- Remote Desktop Connection Manager (RDCMan) 介绍
- 图标修改器html,Iconoid(桌面图标修改器)
- cyusb3014的slavefifo程序的解读
- ThinkPHP3.2短信验证码 (创蓝253短信验证码)
- 100个RPA经典应用场景解析
- @开发者,微软 CEO 萨提亚带领 60 位大咖的集结令,你敢接吗?
- 大盗阿福(打家劫舍)
- 数据库候选关键词怎么求_关系模式中候选关键字的图论求解法