【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、展示

相关推荐
曲幽10 小时前
FastAPI + PostgreSQL 实战:从入门到不踩坑,一次讲透
python·sql·postgresql·fastapi·web·postgres·db·asyncpg
用户83562907805115 小时前
使用 C# 在 Excel 中创建数据透视表
后端·python
码路飞18 小时前
FastMCP 实战:一个 .py 文件,给 Claude Code 装上 3 个超实用工具
python·ai编程·mcp
dev派20 小时前
AI Agent 系统中的常用 Workflow 模式(2) Evaluator-Optimizer模式
python·langchain
天蓝色的鱼鱼1 天前
从“死了么”到“我在”:用uniCloud开发一款温暖人心的App
前端·uni-app
小徐_23331 天前
uni-app 组件库 Wot UI 的 AI 友好型编程指南
前端·uni-app
前端付豪1 天前
AI 数学辅导老师项目构想和初始化
前端·后端·python
用户0332126663671 天前
将 PDF 文档转换为图片【Python 教程】
python
悟空爬虫1 天前
UV实战教程,我啥要从Anaconda切换到uv来管理包?
python
dev派1 天前
AI Agent 系统中的常用 Workflow 模式(1)
python·langchain