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

相关推荐
chao_78910 分钟前
回溯题解——子集【LeetCode】二进制枚举法
开发语言·数据结构·python·算法·leetcode
白杨木影子被拉长23 分钟前
多状态映射不同样式(scss语法)
vue.js·uni-app
一念杂记32 分钟前
免费开源!微信小程序商城源码,快速搭建你的线上商城系统!
微信小程序·uni-app
zdw32 分钟前
fit parse解析佳明.fit 运动数据,模仿zwift数据展示
python
剑桥折刀s1 小时前
Python打卡:Day46
python
巴里巴气1 小时前
Python爬虫图片验证码和滑块验证码识别总结
爬虫·python
sword devil9002 小时前
PYQT实战:智能家居中控
python·智能家居·pyqt
NetX行者2 小时前
FastMCP:用于构建MCP服务器的开源Python框架
服务器·python·开源
超龄超能程序猿2 小时前
(3)机器学习小白入门 YOLOv: 解锁图片分类新技能
python·numpy·pandas·scipy
waynaqua2 小时前
FastAPI开发AI应用一:实现连续多轮对话
python·openai