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

相关推荐
Yvonne爱编码6 分钟前
JAVA数据结构 DAY6-栈和队列
java·开发语言·数据结构·python
前端摸鱼匠1 小时前
YOLOv8 环境配置全攻略:Python、PyTorch 与 CUDA 的和谐共生
人工智能·pytorch·python·yolo·目标检测
WangYaolove13141 小时前
基于python的在线水果销售系统(源码+文档)
python·mysql·django·毕业设计·源码
AALoveTouch1 小时前
大麦网协议分析
javascript·python
ZH15455891311 小时前
Flutter for OpenHarmony Python学习助手实战:自动化脚本开发的实现
python·学习·flutter
xcLeigh2 小时前
Python入门:Python3 requests模块全面学习教程
开发语言·python·学习·模块·python3·requests
xcLeigh2 小时前
Python入门:Python3 statistics模块全面学习教程
开发语言·python·学习·模块·python3·statistics
YongCheng_Liang2 小时前
从零开始学 Python:自动化 / 运维开发实战(核心库 + 3 大实战场景)
python·自动化·运维开发
鸽芷咕2 小时前
为什么越来越多开发者转向 CANN 仓库中的 Python 自动化方案?
python·microsoft·自动化·cann
秋邱2 小时前
用 Python 写出 C++ 的性能?用CANN中PyPTO 算子开发硬核上手指南
开发语言·c++·python