WeChat applet development tutorial: Use nodejs to obtain a set of data from mysql and display it all in the WeChat applet. Data interaction nanny-level tutorial

Last time I wrote an article to display a piece of data in the MySQL database to the front end of the WeChat applet, which is data interaction:

WeChat Mini Program Development Tutorial: Use nodejs to obtain a data from the mysql database and display it on WeChat Mini Program-CSDN BlogThe article has been viewed and read 329 times, liked 8 times, and collected 5 times. In the above code, { {ImgUrl}} parameter is a constructed url path field. You can find its usage in the article I published before. Notice:{ The text in {item.text}} corresponds to the text field in the pop table of the mysql database, { {item.img}}Similarly. Finally, make sure that the server domain name of your WeChat applet has been added to the server domain name whitelist of the WeChat public platform, otherwise the request will fail because the domain name is not in the whitelist. This is a very basic tutorial that will help you use noidejs to get the data you want from the mysql database and display it in the WeChat applet. Callback function to use the returned data to set the data of the applet page. https://blog.csdn.net/qq_25501981/article/details/134728961Now let’s continue to teach you how to use nodejs to convert the data in the mysql database Multiple data are all displayed in the WeChat applet.

The first step is to create a WeChat applet WXML file

This is still a case written by myself. The following is the front-end WXML code of the WeChat applet I wrote:

<button bindtap="showForm" style="width: 35%; background-color: {
   
   {btnColor}}; color: white;" class="view-btn">动态</button>


<view class="cover-pen-dt" wx:if="{
   
   { isShowForm }}" wx:for="{
   
   { wxinfopenList }}" wx:key="{
   
   { index }}">
  <view class="cover-1">
    <view class="avatarbox">
      <image class="avatar" src="{
   
   {item.avatarUrl}}"></image>
      <view class="avatartxt">
        <text class="nickname">{
   
   {item.nickname}}</text>
        <text class="timetxt">发布时间:{
   
   {item.create_time}}</text>
      </view>
    </view>
    <view class="nicknamebox">
      <text class="nickname1">{
   
   { item.text }}</text>
    </view>
    <view class="imgbox">
      <block wx:for="{
   
   { imgPaths[index] }}" wx:key="{
   
   { item }}" wx:for-index="itemIndex">
        <image class="img" src="{
   
   { item }}" bindtap="previewImage" data-index="{
   
   { index }}" data-item-index="{
   
   { itemIndex }}"></image>
      </block>
    </view>
    <view class="btnbox">
      <image class="btntxt" src="../images/jh.png"></image>      
      <div class="btnimglove-container">
      <image class="btnimglove" src="../images/love.png" bindtap="like" data-content-id="{
   
   {item.iddt}}"></image>
      <text class="like-count {
   
   { likeCounts[item.iddt] > 0 ? 'red-background' : '' }}">{
   
   { likeCounts[item.iddt] }}</text>
      </div>

      <div class="btnimg-container">
       <image class="btnimg" src="../images/chat.png" bindtap="showComment" data-content-id="{
   
   {item.iddt}}"></image>
       <text class="comment-count {
   
   { commentCounts[item.iddt] > 0 ? 'red-background' : '' }}">{
   
   { commentCounts[item.iddt] > 0 ? commentCounts[item.iddt] : '' }}</text>
      </div>

    </view>

    <view class="comment2" wx:for="{
   
   { commentListzy[item.iddt] }}" wx:key="{
   
   {index}}" wx:if="{
   
   { commentListzy[item.iddt] }}">
      {
   
   {item.nickname}}: {
   
   { item.comment_text }}
      <text class="reply-button" data-comment-id="{
   
   { item.id }}" data-nickname="{
   
   { item.nickname }}" bindtap="reply">回复</text>
    </view>

   <view class="comment-container">
  <view class="comment" bindtap="showComment1" data-content-id="{
   
   {item.iddt}}">{
   
   { showCommentText}}</view>
    </view>
   </view>

</view>

wx:for="{ { wxinfopenList }}"

The code is a bit long. Let’s look at the beginning first. Have you seen it?wx:for="{ { wxinfopenList }}". This is the template syntax in the WeChat applet. It is an instruction for list rendering and can traverse an array. , and generate template content for each item in the array.

Therefore, we can use this syntax to traverse the data obtained from mysql.

In my example, wx:for="{ { wxinfopenList }}" means that the array wxinfopenList will be traversed. And wxinfopenList contains a series of data. The double curly braces { { }} here are the syntax for data binding, which tells the applet framework that the value of the variable wxinfopenList needs to be bound to this < a i=6> in loop. wx:for

When we use wx:for for list rendering, the WeChat applet will provide a index variable by default to represent the index of the current item, and a attributes. But just take a look at these contents, you don’t need to read them too carefully. and item variable represents the data of the current item. If you need to customize the names of these variables, you can use the wx:for-indexwx:for-item

To put it simply, the function of this code is to traverse each item in the wxinfopenList array, and then generate a series of WXML elements based on the data in the traversal process, thereby dynamically to build the user interface.

{ {item.avatarUrl}}

Then we are talking about code{ {item.nickname}}. In the WeChat applet, { {item.nickname}} is a data binding expression. Here, the double curly brackets { {}} indicate that this is a place for dynamic data binding, and the mini program framework will automatically fill the bound data into this position.

Specifically, item is a variable, which is usually used as the default current item variable name when using wx:for for list rendering, or when developing or a custom variable name. In my case, nickname is an attribute in the item object, which represents the nickname of a user.

For example, if there is a list of users, each user is an object containing various attributes, such as nickname, age , etc., then in When using wx:for to traverse this user list, you can use { {item.nickname}} to display the nickname of each user.

In the WXML template of the mini program, this code is placed in a certain tag. When the mini program is run, it will be replaced with the corresponding item object nickname The actual value of the attribute. In this way, users can see each user's nickname on the mini program interface.

bindtap="showForm"

bindtap="showForm" is an event binding declaration. Here bindtap is the attribute used to bind click events in the WeChat applet, and "showForm" is the name of the function that handles click events. This function needs to be in the applet Defined in the methods of the Page object.

When the user clicks on the element with the attribute bindtap="showForm" , the applet will execute the function named showForm . This function is usually defined in the JavaScript file of the page and is used to handle the logic after the click event, such as displaying a form, changing a data state, navigating to another page, etc.

In my case, when I click the button button with bindtap="showForm" attribute, the content in the code below will be displayed.

Summarize

Currently these are the basic methods of obtaining data from the mysql database and displaying it to the front end of the WeChat applet. As for the wx:for="{ I wrote later { imgPaths[index] }}" and wx:for="{ { commentListzy[item.iddt] }}", I will teach you next time.

The second step is to create a WeChat applet TS file and obtain data from nodejs.

At the beginning of the above code, I also wrote a wx:if="{ { isShowForm }}", which is a conditional rendering instruction that is used to decide whether to render a certain template part based on conditions.

For example, if you have a form and you only want it to be displayed when certain conditions are met, you can use wx:if to control the display and hiding of the form, as follows Show:

<form wx:if="{
   
   { isShowForm }}">
  <!-- 表单内容 -->
</form>

Let's continue. We first need to write in Data:

  data: {
    wxinfopenList: [], // 存储从后台获取的数据。
  },

And then these:

  showForm() {
    if(this.data.btnColor == '#ff00ff'){
        this.setData({
            isShowForm1: false,
            isShowForm2: false,
            isShowForm3: false,
            btnColor: '#662d91',
            btnColor1: '#ff00ff',
            btnColor2: '#ff00ff'
        })
    }else{
        this.setData({
            btnColor: '#ff00ff'
        })
    }
    this.setData({
        isShowForm:!this.data.isShowForm
    })
    wx.request({
        url: config.apiUrl + "/api/getdt",
        success: (res) => {
          const { result, allImagePaths } = res.data;
          this.setData({
            wxinfopenList: result,
            imgPaths: allImagePaths,
          });
        },
      });
},

In the above code, I initiated a network request to obtain the data in mysql. The requested URL is composed of config.apiUrl + "/api/getdt" spliced ​​together. After the request is successful, use the arrow function (res) => {...} to process the response. In the response, it destructures the assignments result and allImagePaths and sets them to wxinfopenList and imgPaths

Here, we ignore allImagePaths  and imgPaths。

setData The method is used to update page data, which causes the page to be re-rendered to reflect the changes in data. Basically, just apply the template and make changes, no need for me to explain.

The third step is to create nodejs routing interface

In my case, the routing interface I created is getdt, and the code is as follows:

const express = require("express");
const router = express.Router();
const multer = require("multer");
const path = require("path");
const db = require("../sql");

// 获取wxinfopen表的数据
router.get("/getdt", (req, res) => {
    //const sql = "SELECT * FROM wxinfopen";
    const sql = "SELECT * FROM wxinfopen INNER JOIN wxusers ON wxinfopen.openid = wxusers.openid ORDER BY wxinfopen.iddt DESC";
    db.query(sql, (err, result) => {
        if (err) {
            console.log(err);
            res.status(500).json({ message: "获取数据失败" });
        } else {
            const allImagePaths = result.map((row) => {
                const imgArr = JSON.parse(row.img || "[]");
                return imgArr.map((imgObj) => "http://localhost:3000/" + imgObj.path.path);
            });
            console.log("成功获取所有的路径,传递这些数据到小程序", allImagePaths,result);
            res.status(200).json({ result, allImagePaths});
        }
    });
});
module.exports = router;

In the above code, we can use const sql = "SELECT * FROM wxinfopen"; to obtain all the data directly and unconditionally, and then pass all the data out through res.status(200).json({ result, allImagePaths});. Here we still ignore allImagePaths. This is the image path array I created. In actual combat, you can delete the code related to allImagePaths. Regarding allImagePaths, I get a set of photos from mysql and display them on the front end of the WeChat applet. This is a bit complicated, so we won’t talk about it here.

The above seems like a lot of code, so let’s look at a simplified version:

const express = require('express');
const router = express.Router();
var db = require('../sql.js');

router.get('/getinfo', (req, res) => {
    const sql = 'SELECT * FROM wxinfopen';
    db.query(sql, (error, results, fields) => {
        if (error) {
            throw error;
        }
        res.json(result);
    });
});

module.exports = router;

Finally, our WeChat applet useswx.request to call this interface to obtain data from the database and send it to the front end of the applet.

Guess you like

Origin blog.csdn.net/qq_25501981/article/details/134747570