第一句子网 - 唯美句子、句子迷、好句子大全
第一句子网 > 【微信小程序】项目开发-----百度翻译API接口开发微信翻译小程序

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

时间:2023-05-28 08:56:18

相关推荐

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

开发环境:

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

开发语言:

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 = '0528000302826'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/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构建:

源码下载:

/download/jockliu/11255020

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。