注册百度翻译开放平台
注册完需要新建一个应用,名字随便,只填名字也行。

通用翻译接入文档
在控制台获取appid和key放到下面代码中

实现
下载axios
main.js中引入axios
import axios from 'axios' Vue.prototype.$http=axios
|
下载js-md5
跨域
官方的请求地址是 https://fanyi-api.baidu.com/api/trans/vip/translate 如果直接在本地使用会出现跨域问题。
解决:
在项目下找到vue.config.js没有就新建一个
const { defineConfig } = require('@vue/cli-service') module.exports = defineConfig({ devServer:{ proxy:"https://api.fanyi.baidu.com" } })
|
完整代码
<template> <div> <div id="div1" contenteditable="true" ref="befco"></div> <div class="block"> <el-button type="primary" @click="tr">翻译</el-button> </div> <div id="div2" contenteditable="true" ref="afco"></div> </div> </template>
<script> import md5 from "js-md5"; export default { data() { return { appid: 'xxxx', key:'xxx', from:'zh', to:'en', content:'' }; }, methods: { tr() { this.content=this.$refs.befco.innerText; if(this.content===''){ this.$message({ showClose: true, message: '翻译的内容不能为空!', type: 'warning' }); }else{ var salt = new Date().getTime(); let str = this.appid + this.content + salt + this.key; var sign = md5(str); console.log(sign); this.$http.get( "/api/trans/vip/translate", { params:{ q: this.content, appid: this.appid, salt: salt, from: this.from, to: this.to, sign: sign } } ).then((res)=>{ console.log(res); this.$refs.afco.innerText=JSON.stringify(res.trans_result[0].dst); }); }; }, }, }; </script>
<style scoped> #div1 { border: 1px solid red; width: 800px; height:150px; }
#div2{ border:1px solid black; width: 800px; height:150px; } </style>
|
效果
