1. Registration event

// bindtap -- Click event

// Use click with 200-300ms delay (workaround)
// 1. Fastclick (plugin) 2. Use tap zepto without click(similar to JQ) 3

// Native JS uses onmousedown + onmouseup directly
// to call MSG in js, use this.data, MSG
// The data in the modified data must be setData. Only setData will trigger the view update
Copy the code

Two-way data binding

// bindinput binds input
<input type="text" style="border: 2rpx solid #000;" value="{{text}}" bindinput="inputFn" />
<text>{{text}}</text>

data:{  text:'Two-way data binding' }

inputFn(e){
	this.setData({
		text:e.detaol.val
	})
}
Copy the code

3. Generate data in a loop

// Block empty tag can be wrapped around b
wx:for- binding wx: ket ='*this'<view Wx:for="{{arr}}" wx:key="*this">{{index}}----{{item}}</view>
// index item is encapsulated
data:{
	arr: ['liu bei'.'guan yu'.'zhang fei'].myarr:[
        {class:1.students: ['the sable cicada'.'fire'.'Joe'] {},class:2.students: ['the sable cicada 1'.Sun '1'.Occasion '1'] {},class:3.students: ['the sable cicada 2'.'fire 2'.Occasion '2']},]}//------------------------------------
<view wx:for="{{myarr}}" wx:key="*this">
    							// rename wx:for-item="el" for easy reading
    <text wx:for="{{item.students}}" wx:key="*this" wx:for-item="el">{{el}}</text>
   	<text>Class is {{item. Class}}</text>
</view>

// wx:key value:
// 1. Index 2. Any field (an attribute of each item) 3

// Get the data from data
// this.data.arr
Copy the code

4. Show and hide

// wx:if -- manipulate DOM show hide false/true -- show/hide destroy
data: {flag: false}
// hidden false/true -- hidden/display (reverse judgment) display = none/block

// wx:if conditional judgment
data: {score :90
}
<view wx:if = "{{score >= 90}}"> good < / view ><view wx:elif = "{{score >= 60}}">Pass the</view>
<view wx:else>Don't pass the</view>
Copy the code

5. Use of WXS module

// Within the < WXS > tag in the WXML file
<view>{{tools.filterPrice(price)}}</view> // 99.00 meta data:{price:99} < WXS module="tools"> /Function filterPrice(val){return "¥" + val.tofixed (2) + 'yuan'} / function filterPrice(val){return "¥" + val.tofixed (2) + 'yuan'} /Module. exports = {filterPrice:filterPrice} </wxs>
// file with the.wxs suffix.
// Write the WXS file and export the methods or variables to use using module.exports
// Use < WXS SRC ="/path" module="tools" /> on the page to be used
// Use tools.method_name in interpolation {{}} (para)
Copy the code

Six, the use of templates

// Create a templates folder in the pages /home/directory to store template files. Let's create a new item.wxml
template name="box1">
  <text bindtap="txtFn">box1: {{content}}</text>
</template>

<import src="./templates/item.wxml" /><template is= is introduced into the page"box1" data="{{content: txt}}"></template>

Bindtap ="txtFn"; the method that implements txtFn needs to be written in the caller's JS file, not in the template's JS file.
// home.js
Page({
  data: {
    txt: 'Crossing the Line'
  },
  // A method that can be called by the template
  txtFn(){
    console.log('print... ')}})Copy the code

Seven, component development

1. Create a component

// It can be created in pages of app.json:
{
  "pages": [..."components/product/product"],}Copy the code

2. Structure, style and data rendering

<view class="product_list">
  <view wx:for="{{showArr}}" wx:key="*this" class="product_list_box">
    <view>{{item.imgTxt}}</view>
	<image src="{{item.imgSrc}}" mode="widthFix"></image>
  </view>
</view>

// Note that the Page() method has been changed to Component()
Component({
  data: {
    showArr: [{imgSrc: "/images/home/newPro1.jpg".imgTxt: "Cappuccino"},
      {imgSrc: "/images/home/newPro2.jpg".imgTxt: "Black coffee"]}})},Copy the code

3. Declare as a component

// In product.json:
{
  "usingComponents": {},
  "component": true
}
Copy the code

4. Invoke the component

In home.json: {"usingComponents": {
    "product-block": "/components/product/product"
  },
  "navigationStyle": "custom" / / custom
}
在 home.wxml 中:
<product-block />
或:
<product-block></product-block>
Copy the code

8. Component value transfer

1. Father passes son

// Use the above example to put the data into the data in home.js
/ / child component
<product-block showArr="{{showArr}}" />
 / / the product. In js:
 Component({
  // properties is used to receive passed values, similar to props in vue
  properties: {
    SongArr: {
      // Set the data type
      type: Array.// Set the initial value (default value)
      value: [{imgSrc: "/images/home/newPro1.jpg".imgTxt: "Cappuccino"}]
       // Determine the array as the data type
       value: []}}})/ / rendering
<view class="product_list">
  <view wx:for="{{SongArr}}" wx:key="*this" class="product_list_box">
    <view>{{item.imgTxt}}</view>
	<image src="{{item.imgSrc}}" mode="widthFix"></image>
  </view>
</view>

Copy the code

Son to father

// Click any item in the Product component to trigger the parent event.
/ / child component
<view class="product_list">
  <view wx:for="{{showArr}}" wx:key="*this" class="product_list_box" bindtap="productTap">.</view>
</view>

// components/product/product.jsComponent({ ... .// If it is a component, not a page, you must write methods
  methods: {
    productTap(){
  		// Applet parenting is implemented by triggerEvent
      this.triggerEvent('fatherEvent'.100); }}}) <! -- Use bind on the tag to receive events from child components --><product-block  bind:fatherEvent="Event name" />Page({ ... .// The page does not need to write methodsThe event name (event) {console.log(event.detail); / / 100}})Copy the code

Global variable globalData

Const app = getApp()

const app = getApp()
Page({
  onLoad: function () {
    console.log(app.globalData.name); }})Copy the code

Const app = getApp(); globalData = getApp()

onLoad: function () {
    console.log(getApp().globalData.name);
},
Copy the code

[Method 3] Use it in app.js file

onLoad: function () {
    console.log(this.globalData.name);
},
Copy the code

9. Route redirection

1. Jump to the non-Tabbar page

wx.navigateTo({
    url: '/pages/logs/logs'
})
// The url takes the form of a parameter:
wx.navigateTo({
    url: '/pages/logs/logs? id=123',})// How to get parameters?
onLoad: function (options) {
    console.log(options.id)		/ / 123
},
    
// A form that takes complex parameters
wx.navigateTo({
    url: '/pages/logs/logs? id=123'.success: function(res) {
        // Send data to the opened page via eventChannel
        res.eventChannel.emit('someData', { arr: [1.2.3]})}})// Accept the form of complex parameters
onLoad: function (options) {
    console.log(options.id)		/ / 123
    const eventChannel = this.getOpenerEventChannel()// Get the parameters through eventChannel
    eventChannel.on('someData'.function(data) {
        console.log(data.arr)	/ / [1, 2, 3]})},// The current page sends data back to the previous page
onLoad: function (options) {
    const eventChannel = this.getOpenerEventChannel()
    // Reverse transmit data
    eventChannel.emit('fanxiang', {username: 'Joe'});
},
// The previous page receives data transmitted in reverse
wx.navigateTo({
    url: '/pages/list/list? id=123'.// events to write the reverse emission function
    events: {
        fanxiang(data){
            console.log(data)
        }
    }
})
Copy the code

2. Jump to non-Tabbar page (WXML)

<navigator url="/pages/logs/logs"></navigator>
Copy the code

3. Go to the Tabbar page

wx.switchTab({
    url: '/pages/user/user'
})
Copy the code

X. Life cycle

1. Page lifecycle:

onLoad > onShow > onReady > onHide > onShow > onUnload

2. Component lifecycle

Component({
  lifetimes: {
    attached: function() {
      // Executed when the component instance enters the page node tree
    },
    detached: function() {
      // Executed when the component instance is removed from the page node tree}}})Copy the code

11. Data request

wx.request({
  url: 'http://XXXXXXXXXXXXX.com'.success(res){
    console.log(res); }})Copy the code
Request. js is used to encapsulate requests, generally we leave it alone. Api.js is used to unify the Restful interface address and baseUrl fetch3Set of templates, we can directly copy use// Data request wrapper creates request folder and pages equivalent

// request/api.js
// The developed server
var baseUrl = 'http://xxxxxxx'
// Test the server
// var baseUrl = 'http://xxxx'
// Formal environment
// var baseUrl = 'http://xxxx'
// Home page data request
var indexApi = baseUrl + '/index/index'
/ / export
module.exports = { indexApi }

// request/fetch.js
var api = require('./api.js')
var request = require('./request.js')
// GET requests do not carry parameters
function getHome() {
  return request.requestApi({
    url: api.homeApi
  })
}
// GET requests carry parameters
function getList(params) {
  return request.requestApi({
    url: api.listApi,
    data: params,
  })
}
/ / post request
function LoginFn(params) {
  return request.requestApi({
    url: api.loginApi,
    data: params,
    header: {
      'content-type': 'application/x-www-form-urlencoded'
    },
    method: 'POST'})}// Home page request
function indexApi() {
  return request.requestApi({
    url: api.indexApi
  })
}
module.exports = {
  indexApi: indexApi,
}

// request/request.js
function request(params) {
  // Encapsulates the network request code
  return new Promise(function (resolve, reject) {
    wx.showLoading({
      title: 'Loading... ',
    })
    wx.request({
      url: params.url,
      data: params.data || {},
      header: params.header || {},
      method: params.method || 'GET'.dataType: 'json'.success: function(res) {
        wx.hideLoading()
        resolve(res.data)
      },
      fail: function(err) {
        wx.showToast({
          title: err || 'Request error! ',
        })
        reject(err)
      }
    })
  }) 
}
// nodejs common
module.exports = {
  requestApi: request
}

// page import
const { indexApi } = require(".. /.. /request/fetch.js")
Copy the code

“Vant Retry P

Vant – contrib. Gitee. IO/vant weapp /…

The interview questions

This. SetData of the applet

// Resolve setData performance issues to reduce usage
this.setData(obj,callback) Data updates are synchronous and view updates are asynchronousCopy the code

The life cycle of an applets application

OnLaunch () is triggered when the user launches the applets for the first time (globally only once). OnShow () is triggered when the applets are initialized. OnHide () is also triggered when an applet enters the foreground from the background. OnError () is triggered when a script error or API call failsCopy the code

Applets page life cycle function?

OnLoad () is triggered when the page is loaded and is called only once to get the parameters in the current page path. OnShow () is triggered when the page is displayed/cut to the foreground, usually used to send data requests; OnReady () is called only once when the first rendering of the page is complete, indicating that the page is ready to interact with the view layer. OnHide () Triggered when a page is hidden or accessed in the background, for example, the bottom TAB is switched to another page or a small program is accessed in the background. OnUnload () is triggered when a page is unloaded, such as redirectTo or navigateBack to another page.Copy the code

Brief introduction of micro channel small program principle

  • The essence of small program is a single page application, all page rendering and event processing, are carried out in a page, but can call a variety of native interfaces through wechat client;
  • Its architecture is data-driven architecture mode. Its UI and data are separated. All page updates need to be realized through changes to data.
  • It is similar to the existing front-end development in terms of technology, using JavaScript, WXML, WXSS three technologies for development;
  • Functions can be divided into webView and appService two parts;
  • Webview is used to present UI, appService is used to handle business logic, data and interface calls;
  • The two parts run in two processes and communicate through the system layer JSBridge to achieve UI rendering and event processing

Routing of applets

** Open a new page: ** Call API wx.navigateTo

** Page redirection: ** Calls API wx.redirectTo

NavigateBack: ** Calls API wx.navigateBack

**Tab switch: ** Call API wx.switchTab

** Restart: ** Call API wx.reLaunch

Data cache

// add new cache variable username to "Chen"
// wx.setStorageSync(string key, any data)
wx.setStorageSync('username'.'Chen')
// find - cache variable username
any wx.getStorageSync(string key)
const name = wx.getStorageSync('username')
// Modify - cache variable username
// wx.setStorageSync(string key, any data)
wx.setStorageSync('username'.'Brother Chen')
// Delete the cache variable username
// wx.removeStorage(Object object)
wx.removeStorageSync('username')
// Clear all cache variables
// wx.clearStorage(Object object)
wx.clearStorageSync()
Copy the code