Environment construction and basic use of WeChat applet + Vant-weapp with charts and maps

Environmental preparation

Project initialization configuration

  • In the local settings, close the verification of the domain name, because the port that the WeChat applet wants to go online can only use the https protocol, but it can be set during development.
    insert image description here

  • Remove useless code and files

    1. Delete page->log page
    2. Delete all useless codes of page->Index
    // index.js
    Page({
          
          
      data: {
          
          
      },
      onLoad() {
          
          
     
      },
      login(){
          
          
        console.log('点击');
    
      }
    })
    
    
    1. delete utils->util.js
    2. Delete useless code in app.js
    App({
          
          
      onLaunch() {
          
          
      }
    })
    
    1. Delete the log page configured in app.json
  • Encapsulation request
    Create a js file under utils, the name can be called request.js, and then copy the following encapsulated code

    // 同时发送异步请求的次数
    let ajaxTimes = 0;
    export const request = (params) => {
          
          
      ajaxTimes ++;
      wx.showLoading({
          
          
        title: '加载中',
        mask: true
      })
      
      // 后台的请求地址,记得修改成你自己的地址
      const baseUrl = 'http://localhost:8888';
      
      return new Promise((resolve, reject) => {
          
          
        wx.request({
          
          
          ...params,
          url: baseUrl + params.url,
          success: (result) => {
          
          
            resolve(result.data);
          },
          fail: (err) => {
          
          
            reject(err);
          },
          complete: () => {
          
          
            ajaxTimes --;
            if(ajaxTimes === 0) {
          
            // 所有请求都完成后再关闭提示
              wx.hideLoading();
            }
          },
        })
      })
    }
    

    At this time, an error may be reported: the applet has been ignored by the code dependency analysis and cannot be referenced by other modules. You can modify the code according to the [Code Dependency Analysis] warning message in the console, or turn off the [Filter Non-Dependent Files] function

    Just paste these two configurations into project.config.json=> settinginside

    "ignoreDevUnusedFiles": false,
    "ignoreUploadUnusedFiles": false,
    

    Then go import like this and use e.g.
    insert image description here

  • Configure the tabbar and global styles app.json(no need to configure the page without creating it), for example, here I created another mypage
    insert image description here
    insert image description here
    insert image description here

    "tabBar": {
          
          
        "list": [{
          
          
          "pagePath": "pages/index/index",
          "text": "首页",
          "iconPath": "imgs/home_no.png",
          "selectedIconPath": "imgs/home_yes.png"
        },
        {
          
          
          "pagePath": "pages/login/login",
          "text": "我的",
          "iconPath": "imgs/me_no.png",
          "selectedIconPath": "imgs/me_yes.png"
        }
      ]
      }
    

Download and use Vant

Official website link https://vant-contrib.gitee.io/vant-weapp/0.x/#/quickstart

  • After the WeChat applet initial project is created, go to the directory where the root path of the project is located, open the terminal and use the command npm init -y to build a webpack initialization project
  • Enter again npm i vant-weapp -S --productionto download
  • Select build npm in the toolbar and
    insert image description here
    the download of vant is completed here, but before using each component, it must be imported app.json(globally valid) or index.jsonin the page where it is located (only valid on this page)
    . For example, to be in Introduce a vant button component globally, and you will be prompted on the official website how to import it.
    insert image description here
    Such a direct import may report an error that the file cannot be found!!!

Solution 1 : Simulate the introduction of some buttons in the official document to get started quickly, and replace the button with the corresponding component
* For example, I want to introduce an input box, check the official website to know the word of the input box is field, so refer to the button to infer the introduction of the input The method is to
insert image description here
use can directly copy the official website on the corresponding page

Solution 2 : Define the path yourself
or introduce the input box, you can use it
insert image description here
to find the corresponding location step by step according to the compiler prompts

After copying, put it in this location
insert image description here
and then copy the label and style of the corresponding component on the applet page

  • Remove the in app.json "style": "v2",because the style of the v2 version may overwrite the original style of the component

Introduce wxcharts

Introduce Gaode map

Note that the key of the Gaode map WeChat applet and the key of the web page cannot be mixed. There needs to be a separate key for the applet . This key does not have a secret key yet.

  • Go to the official website of Gaode map to download the js package of Gaode map, https://lbs.amap.com/api/wx/download , unzip it and get a package amap-wx.130.jsthat can be put utilsinto the package

  • Like wxchart, in the required page, import its js package
    insert image description here

  • app.jsonConfigure authorization in

    "permission": {
          
          
            "scope.userLocation": {
          
          
                "desc": "点击确认"
            }
        },
    

    insert image description here

    <view class="map_container">
      <map class="map" name="" longitude="{
          
          {longitude}}" latitude="{
          
          {latitude}}" scale="16"  show-location="true" markers="{
          
          {markers}}">
      </map>
    </view>
    <view class="map_text">
      <text class="h1">{
          
          {
          
          textData.name}}</text>
      <text>{
          
          {
          
          textData.desc}}</text>
    </view>
    

The construction of the environment here is basically completed.

use

wxchart uses

1. Specify the box in wxml 2. Create an object in js to draw the chart and display it in the box

  • Specify the position and size of the chart display in wxml. To use it <canvas>标签, the id of the label becomes the position mark of the chart display, and the class is used to write the style in wxss. 一定要指定大小Otherwise, it will not be displayed
    	<canvas canvas-id="columnCanvas" disable-scroll="true" class="canvas"></canvas>
    
  • In the js code of the page to be imported, import the js package of wxchats
    insert image description here
  • dataDefine the dynamic variables required by the chart in , receive the data brought back by the request from the backend in , onShow()and assign values ​​to the variables in data. In onshow()the method, start to create wxChartsobjects and set chart data. For details, please refer to this article https://www.cnblogs.com/xiaobai-y/p/9089157.html .

Summary:wxml Specify the canvas in - <canvas>> wxssSpecify the position of the canvas display, size, style beautification, etc. -> daraSet the dynamic data required by the chart in -> onLoad()Send a request to get the back-end data in and update the data Variables are assigned. -> onShow()Render graphics in, for display

Use of Gaode map

It is the same as the usage process of the above chart. It is worth noting that the map information is displayed in the wxml tag attribute, and js only obtains data and assigns values ​​to the data without rendering the map.

  • Specify the information to be displayed on the map in the wxml page, such as position, length and width, map center, marked points, etc. Create a map object in js, then call the method, and assign values ​​to the variables in wxml in the successful callback method to display the map information

  • Location function If I want to get the current user location and draw it as a point on the map

    wxml specifies the map display on the page, leaving the location of the data
    insert image description here

    <view class="map_box">
      <map id="navi_map" longitude="{
          
          {longitude}}" latitude="{
          
          {latitude}}" scale="15" markers="{
          
          {markers}}"></map>
    </view>
    

    The onLoad of
    insert image description here
    the data part of the js in the wxss part calls different map object apis here according to different geographic location requirements
    insert image description here


    insert image description here

    var myAmap= new amapFile.AMapWX({
          
          
        key:'353e57c983700f2d920ca2c709013cbe'
      })
      myAmap.getRegeo({
          
          
        success:(data)=>{
          
          
          this.setData({
          
          
            latitude:data[0].latitude,
            longitude:data[0].longitude
          })
          var marker={
          
          }
          marker.latitude=data[0].latitude,
          marker.longitude=data[0].longitude,
          marker.id=data[0].id,
          marker.width=23,
          marker.height=33
          var markArr=[]
          
          markArr.push(marker)
          this.setData({
          
          
            markers:markArr
          })
        },
        fail:()=>{
          
          
          console.log('获取地理位置坐标失败');
        }
      })
    

    The output of the above function, datathe data displayed in, the data is very much!
    insert image description here
    Effect:
    insert image description here

  • Keyword search function
    Pass the search keyword in js querykeywords, call getPoiAroundthe method of the map object, and display nearby point information in the callback
    insert image description here

  • Bind the click event to the point

在map标签中 添加属性 bindmarkertap="绑定的函数名xxx" ,在js中此函数的参数中会传递该点的id序号,然后在保存点的数组中通过id序号即可找到点的信息、对象等。实现对点的修改

insert image description here

Use of vant Weapp

List the problems I encountered when using it again

  • The imported style cannot be imported according to the given import method of the component, and it may appear that the component cannot be found
    insert image description here

  • The main button is blue on the official website, but green in WeChat

  • The button component cannot specify a style, and it is invalid whether using an inline style or a class.
    insert image description here
    My solution is to directly view the style class of the component pair and rewrite it in the class
    insert image description here

  • The Filed input box provided by the official website needs to be passed bind:changeand then the value of the input box is obtained in the bound function event.detail. Each data box must have a corresponding event. It
    can also be achieved in this way model:value="{ { xxx }}", that is, add the model before the value variable

notes

  • To realize the page dynamic title setting, you can call the wx api setting in the onShow() method of the page
onShow() {
    
    
        wx.setNavigationBarTitle({
    
    
            title: "个人中心"
        })  
    },
  • The jumping method of the tabBar page is different from that of the normal page
tabBar的路由方式跳转
  wx.switchTab({
    
    
    url: '../xxx/xxx'
})
普通页面的路由跳转
 wx.navigateTo({
    
    
    url: '../xxx/xxxx',
})
  • The tips of the applet can be used wx.showToast()
 wx.showToast({
    
    
      title: '请先登录',
      icon: 'error'/'success'/'loading'/不写(即只定时显示文字)
    })
    还可以在对象中指定延迟 duration  默认延迟1500
  • The way the applet sets variables in data
    is similar to react. You need to use the wx.setData({data attribute variable: xxx}) method.
    insert image description here
    For assignment in the form of objects, you need to use ['a.b'] to wrap

  • How to share the developed program with others?

    • First of all, you cannot use the test account for development when creating a project. You must use your own registered APPID, so that you can use your own account to log in for background management. WeChat Xiaochengxun background management URL https://mp.weixin.qq.com/ , you must choose your own appId applet when logging in
    • Open here, if the applet does not click upload, there will not be any version here
      insert image description here
  • Upload your own applet to the development management platform to form a version,
    insert image description here
    and then you will see it on the management platform
    insert image description here

  • Select experience, then add the WeChat account number of the experiencer, and send the QR code of the WeChat mini program trial version to the set experiencer, who can scan the code and use it, and the code will not expire. Be sure to set the
    experiencer , other People can't scan the code

Guess you like

Origin blog.csdn.net/m0_52889702/article/details/128278294