【uniapp】使用uniapp实现一个输入英文单词翻译组件

目录

1、组件代码

2、组件代码

3、调用页面

4、展示


前言:使用uniapp调用一个在线单词翻译功能

1、组件代码

2、组件代码

YouDaoWordTranslator

复制代码
<template>
  <view class="translator">
    <input class="ipttext" type="text" v-model="query" placeholder="请输入单词" />
    <!-- <button @click="fetchData">查询</button> -->
    <view class="showblock" v-if="result.length">
      <text class="showtext" v-for="(item, index) in result" :key="index">解释 {{ index + 1 }}: {{ item }}</text>
    </view>
  </view>
</template>

<script setup>
import { api } from '../../config/settings';
import { ref, watch } from 'vue';

const query = ref('');
const result = ref([]);

const fetchData = () => {  
  const url = api.defineword + '?q=' + query.value; 
  console.log(url);

  uni.request({
    url: url,
    method: 'GET',
    header: {
      'Content-Type': 'application/json'
    },
    success: (res) => {
      console.log('响应数据:', res);
      if (res.statusCode === 200 && res.data && res.data.data && res.data.data.entries) {
        // 获取entries数组中每个元素的explain属性并存放到result数组中
        result.value = res.data.data.entries.map(item => item.explain);
        console.log(result.value);
      } else {
        console.error('请求失败或数据格式不正确:', res);
      }
    },
    fail: (err) => {
      console.error('请求失败:', err);
    }
  });
};

// 监听查询字符串的变化,以便在输入时自动调用fetchData
watch(query, (newQuery) => {
  if (newQuery) {
    fetchData();
  } else {
    // 当输入框内容为空时,清空结果数组
    result.value = [];
  }
});
</script>

<style scoped>
/* 你的样式 */
.ipttext {
  margin-top: 10rpx;
  height: 50rpx;
  margin-bottom: 10rpx;
}
.showblock {
  background-color: azure;
}
</style>

3、调用页面

wordTranslator

复制代码
<template>
  <translator />
</template>

<script setup>
import Translator from '@/components/YouDaoWordTranslator/YouDaoWordTranslator.vue';


</script>

4、展示

相关推荐
IVEN_16 小时前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang18 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮18 小时前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling18 小时前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python
AI攻城狮21 小时前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维
曲幽21 小时前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
小时前端21 小时前
微信小程序选不了本地文件?用 web-view + H5 一招搞定
前端·微信小程序·uni-app
孟健2 天前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞2 天前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python