uni-app 天气插件

uni-app 天气插件

有大佬写成的uni-app天气插件吗?

2 回复

同求啊,大佬

更多关于uni-app 天气插件的实战教程也可以访问 https://www.itying.com/category-93-b0.html


当然,下面是一个简单的 uni-app 天气插件的实现示例。这个示例将展示如何使用 uni-app 和一个免费的天气 API 来获取并显示天气信息。

首先,确保你已经在项目中安装了 uni-app 相关的依赖,并且已经创建了一个基本的项目结构。

1. 安装请求库

uni-app 中,我们通常使用 uni.request 来发送网络请求。不过,为了代码的简洁性,我们可以使用 axios(虽然它不是 uni-app 官方的库,但可以在 HBuilderX 中正常使用)。

npm install axios

2. 创建天气组件

components 目录下创建一个名为 Weather.vue 的组件。

<template>
  <view>
    <text v-if="loading">加载中...</text>
    <view v-else>
      <text>城市: {{ weather.location.name }}</text>
      <text>天气: {{ weather.current.text }}</text>
      <text>温度: {{ weather.current.temp }}°C</text>
    </view>
  </view>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      weather: {},
      loading: true,
    };
  },
  created() {
    this.getWeather('北京'); // 你可以将这里改为动态获取城市名
  },
  methods: {
    async getWeather(city) {
      try {
        const response = await axios.get(`https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=${city}`);
        this.weather = response.data;
      } catch (error) {
        console.error('获取天气信息失败', error);
      } finally {
        this.loading = false;
      }
    },
  },
};
</script>

3. 使用天气组件

pages/index/index.vue 中引入并使用这个天气组件。

<template>
  <view>
    <Weather />
  </view>
</template>

<script>
import Weather from '@/components/Weather.vue';

export default {
  components: {
    Weather,
  },
};
</script>

注意事项

  1. API Key:在上面的代码中,你需要替换 YOUR_API_KEY 为你从天气 API 服务提供商那里获取的 API Key。
  2. 跨域问题:在开发阶段,如果遇到跨域问题,可以在 manifest.json 中配置代理。
  3. 动态获取城市:上面的示例中城市是硬编码的,你可以通过输入框让用户输入城市名,然后动态调用 getWeather 方法。

这样,你就创建了一个简单的 uni-app 天气插件。根据需求,你可以进一步扩展功能,比如添加未来几天的天气预报、错误处理等。

回到顶部