WeChat applet generates a weather query applet

WeChat applet generates a weather query applet

Basic page structure and logic

Page structure: includes an input box and a query button.
Page logic: After the user enters the city name, click the query button to jump to the weather details page, and pass the city name as a parameter.

main code

index.js

// index.js
Page({
    
    
  data: {
    
    
    city: ''
  },
  onInput: function(e) {
    
    
    this.setData({
    
    
      city: e.detail.value
    });
  },
  onSearch: function() {
    
    
    wx.navigateTo({
    
    
      url: '/pages/weather?city=' + this.data.city
    });
  }
});

index.wxml

<!-- index.wxml -->
<view class="container">
  <input type="text" placeholder="请输入城市名称" bindinput="onInput"></input>
  <button bindtap="onSearch">查询</button>
</view>

index.wxss

/* index.wxss */
.container {
    
    
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
}

Weather details page (pages/weather)

weather.js

// weather.js
Page({
    
    
  data: {
    
    
    city: '',
    weather: ''
  },
  onLoad: function(options) {
    
    
    const city = options.city;
    this.setData({
    
    
      city: city
    });
    // 请求天气数据
    wx.request({
    
    
      url: 'https://api.weather.com/v1/current?city=' + city,
      success: res => {
    
    
        this.setData({
    
    
          weather: res.data.weather
        });
      }
    });
  }
});

weather.wxml

<!-- weather.wxml -->
<view class="container">
  <view class="weather-info">{
    
    {
    
     weather }}</view>
</view>

weather.wxss

/* weather.wxss */
.container {
    
    
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
}
.weather-info {
    
    
  font-size: 20px;
}

explain

Home page and weather details page. Users can enter the city name on the homepage and click the query button to jump to the weather details page and display the city's real-time weather information.

Please note that in actual use, you need to replace the API address and parameters for requesting weather data with a real and available weather data interface.

That’s the end here, I hope it helps.

Guess you like

Origin blog.csdn.net/weixin_71893790/article/details/135175224