Introduction and use of WeChat applet background data interaction and wxs file

Prepare backstage

Background source code sharing. . . .

ssm-oa.rar - Lan Zuoyun

Front-end test code sharing

oa-mini.rar - Lan Zuoyun

Front-end sending request encapsulation

Promise

Promises are a solution to asynchronous programming that are more logical and powerful than traditional solutions - callback functions and events. It was first proposed and implemented by the community. ES6 wrote it into the language standard, unified usage, and provided Promise objects natively.

The so-called Promise is simply a container that holds the result of an event (usually an asynchronous operation) that will end in the future. Syntactically, a Promise is an object from which messages of an asynchronous operation can be obtained. Promise provides a unified API, and various asynchronous operations can be processed in the same way.

  • There are three states in the promise operation:
    • pending: waiting (in progress) as soon as the promise is created, the pending is in progress
    • fulfilled: success (completed), calling resolve will change the state from pending to fulfilled, and will be executed in the future.then
    • rejected: failure (rejection), calling reject will change the status from pending to rejected, and will execute .catch in the future
  • be careful:
    • Once the state of the promise changes, the state will be frozen
    • If you call reject or resolve again, it is meaningless to modify the state

Registration request interface address

Create config/api.js

 

// 以下是业务服务器API地址
 // 本机开发API地址
 var WxApiRoot = 'http://localhost:8080/wx/';
 // 测试环境部署api地址
 // var WxApiRoot = 'http://192.168.0.101:8070/demo/wx/';
 // 线上平台api地址
 //var WxApiRoot = 'https://www.oa-mini.com/demo/wx/';
 
 module.exports = {
  IndexUrl: WxApiRoot + 'home/index', //首页数据接口
  SwiperImgs: WxApiRoot+'swiperImgs',
  MettingInfos: WxApiRoot+'meeting/list',
  AuthLoginByWeixin: WxApiRoot + 'auth/login_by_weixin', //微信登录
  UserIndex: WxApiRoot + 'user/index', //个人页面用户相关信息
  AuthLogout: WxApiRoot + 'auth/logout', //账号登出
  AuthBindPhone: WxApiRoot + 'auth/bindPhone' //绑定微信手机号
 };

encapsulation request

in /utils/util.js

/**
 * 封装微信的request请求
 */
function request(url, data = {}, method = "GET") {
  return new Promise(function (resolve, reject) {
    wx.request({
      url: url,
      data: data,
      method: method,
      header: {
        'Content-Type': 'application/json',
      },
      success: function (res) {
        if (res.statusCode == 200) {
            resolve(res.data);//会把进行中改变成已成功
        } else {
          reject(res.errMsg);//会把进行中改变成已失败
        }
      },
      fail: function (err) {
        reject(err)
      }
    })
  });
}

 

send request

Use the method in the life cycle function to see the data returned by the background after the page is loaded

 

 

loadMeetingInfos(){
    let that=this;
    // wx.request({
    //     url: api.MettingInfos,
    //     dataType: 'json',
    //     success(res) {
    //       console.log(res)
    //       that.setData({
    //           lists:res.data.lists
    //       })
    //     }
    //   })
    util.request(api.IndexUrl).then(res=>{
        console.log(res))
      this.setData({
        lists:res.data.infoList
      })
    }).catch(res=>{
        console.log('服器没有开启,使用模拟数据!')
    })
  }

Use of WXS module

WeChat official document address

 

index.wxml

<view class="container">
<view>{
   
   {common.msg}}</view>
<view>{
   
   {common.foo}}</view>
<view>{
   
   {foo.value}}</view>
</view>
<!-- module 当前 <wxs> 标签的模块名。必填字段。 -->
<!-- src 引用 .wxs 文件的相对路径。仅当本标签为单闭合标签或标签的内容为空时有效。 -->
<!-- 单标签 引入wxs文件-->
<wxs src="../wxs/common.wxs" module="common" />
<!-- 双标签 -->
<wxs module="foo">
var common = require('../wxs/common.wxs')
// 在.wxs模块中引用其他 wxs 文件模块, 可以使用 require 函数。
module.exports = {
value: common.inArray([1, 2, 3], 1)
}
// 方法一:单行注释
/*
方法二:多行注释
//
方法三:结尾注释。即从 /* 开始往后的所有 WXS 代码均被注释
</wxs>

index.wxss

.container{
height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: flex-start;
box-sizing: border-box;
background-color: rgb(240, 240, 240);
}

common.wxs

var foo="'hello world' from common.wxs"
//inArray方法  判断数组中是否存在某元素
function inArray(arr,val){
return arr.indexOf(val)>-1
}
var msg="some msg"
//module 对象  每个 wxs 模块均有一个内置的 module 对象。
//属性  exports: 通过该属性,可以对外共享本模块的私有变量与函数。
module.exports={
foo:foo,
inArray:inArray
}
module.exports.msg=msg

 

Cautions for using WXS

WXS module

WXS code can be written in tags in the wxml file, or in a file with a .wxs extension.

module

  • Each .wxs file and tag is a separate module.
  • Each module has its own independent scope. That is, variables and functions defined in a module are private by default and invisible to other modules.
  • If a module wants to expose its internal private variables and functions, it can only be realized through module.exports.

require function

  • To refer to other wxs file modules in the .wxs module, you can use the require function.
  • When citing, pay attention to the following points:
  • Only .wxs file modules can be referenced, and relative paths must be used.
  • All wxs modules are singletons. When a wxs module is referenced for the first time, it will be automatically initialized as a singleton object. Multiple pages, multiple places, and multiple references all use the same wxs module object.
  • If a wxs module has not been referenced after its definition, the module will not be parsed and run.

<wxs> tag

attribute name

Types of

Defaults

illustrate

module

String

The module name of the current tab. Required field.

src

String

Refers to the relative path of the .wxs file. Only valid when this tag is a single closed tag or the content of the tag is empty.

module attribute

  • The module attribute is the module name of the current <wxs> tag. Within a single wxml file, it is recommended that its value be unique. If there are duplicate module names, they will be overwritten in order (the latter overwrites the former). wxs module names between different files do not overwrite each other.
  • The naming of module attribute values ​​must comply with the following two rules:

The first character must be: letter (a-zA-Z), underscore ( )

The remaining characters can be: letters (a-zA-Z), underscore ( ), numbers (0-9)

src attribute

  • The src attribute can be used to reference other wxs file modules.
  • When citing, pay attention to the following points:

Only .wxs file modules can be referenced, and relative paths must be used.

All wxs modules are singletons. When a wxs module is referenced for the first time, it will be automatically initialized as a singleton object. Multiple pages, multiple places, and multiple references all use the same wxs module object.

If a wxs module has not been referenced after its definition, the module will not be parsed and run.

Notice

  • < wxs > Modules are only accessible within the WXML file that defines the module. When using or , the module will not be imported into the corresponding WXML file.
  • In the <template> tag, only the <wxs> module defined in the WXML file that defines the <template> can be used.

variable

concept

does not support let const

Variables in WXS are references to values.

Variables that are not declared are directly assigned and used, and will be defined as global variables.

If you declare a variable without assigning a value, the default value is undefined.

The performance of var is consistent with javascript, and there will be variable promotion.

var foo = 1
;var bar = "hello world";
var i; // i === undefined

The above code declares the three variables foo, bar and i respectively. Then, foo is assigned the value 1 and bar is assigned the string "hello world".

variable name

  • Variable naming must comply with the following two rules:
  • The first character must be: letter (a-zA-Z), underscore ()

The remaining characters can be: letters (a-zA-Z), underscore (), numbers (0-9)

reserved identifier

The following identifiers cannot be used as variable names:

delete
void
typeof
null
undefined
NaN
Infinity
var
if
else
true
false
require
this
function
arguments
return
for
while
do
break
continue
switch
case
default

note

<!-- wxml -->
<wxs module="sample">
// 方法一:单行注释
/*
方法二:多行注释
//
方法三:结尾注释。即从 /* 开始往后的所有 WXS 代码均被注释
var a = 1;
var b = 2;
var c = "fake";
</wxs>

Guess you like

Origin blog.csdn.net/qq_62898618/article/details/128627898